Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Zero to Real-Time AngularJS in 60 Seconds

Sunny Gleason
September 03, 2014

Zero to Real-Time AngularJS in 60 Seconds

The way we build web & mobile applications is rapidly changing. As AngularJS developers, we're already familiar with the powerful shift from fine-grained server-side pages to single-page web applications and REST APIs. Now, we're starting to see a potentially even more powerful advance as applications transition from blindly "pulling" content to receiving immediate "push" content in web and mobile applications using technologies like WebSocket.

In this talk, I'll present a chat application I built in 99 lines of HTML & JavaScript using AngularJS and the PubNubAngularJS API. The examples live in codepen.io so everyone will be able to fiddle with the example as we go. Along the way,we'll also talk about some of the patterns and nifty tricks we used to adapt a callback-oriented JavaScript API into the world of AngularJS scopes, services and events.

Bio:
Sunny is founder and Cloud Guy at SunnyCloud, a company that provides Cloud, Web & Mobile application development, hosting and operations to businesses in the cloud. He specializes in real-time protocols and scalable persistence solutions. Before all that, Sunny was a Platform Engineer developing Cloud Computing solutions at Ning and Amazon.com.

Sunny Gleason

September 03, 2014
Tweet

More Decks by Sunny Gleason

Other Decks in Technology

Transcript

  1. Zero to Real-Time
 AngularJS in
 60 Seconds Sunny Gleason Boston

    AngularJS Meetup September 3, 2014 http://goo.gl/KDa5j3
  2. var self = this; • Sunny Gleason, All-Stack Engineer •

    Previous: Amazon (web services), Ning, Startup(1..N) • Current: SunnyCloud • Short Story: A-Team you can call on to help you build (or rescue) cloud services, web & mobile applications • Longer Story: Network of developers aiming to change the way businesses build applications
  3. what does it do? 
 į subscribe to a real-time

    channel display a list of online users show the list of recent messages publish messages to the channel
  4. the html (1) <script src=“https://cdn.pubnub.com/pubnub.min.js" />! <script src=“//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js" />! <script

    src=“http://pubnub.github.io/pubnub-angular/lib/pubnub-angular.js" />! <link rel="stylesheet"
 href=“//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css" /> • include PubNub data stream network • include AngularJS library • include PubNub / AngularJS library • include Bootstrap styles (optional)
  5. the html (4) <form ng-submit='publish()'>! <input type="text" ng-model='newMessage' />! <input

    type="submit" value="Send" />! </form> • Create a form • Bind a text input as chat message input • Bind form submission to ‘publish()’
  6. the js (1) angular.module('PubNubAngularApp', ["pubnub.angular.service"])! .controller('ChatCtrl', function($rootScope, $scope, PubNub) {

    • Create an AngularJS application • Depend on pubnub.angular.service • Create a controller • Inject $rootScope, $scope, PubNub
  7. the js (2) // make up a user id (you

    probably already have this)! $scope.userId = "User " + Math.round(Math.random() * 1000);! // make up a channel name! $scope.channel = 'The Angular Channel';! // pre-populate any existing messages (just an AngularJS scope object)! $scope.messages = ['Welcome to ' + $scope.channel]; • Create a random user id • Put the channel name in $scope • Initialize messages array
  8. the js (3) if (!$rootScope.initialized) {! // Initialize the PubNub

    service! PubNub.init({! subscribe_key: 'demo',! publish_key: 'demo',! uuid:$scope.userId! });! $rootScope.initialized = true;! } • Initialize the PubNub service • Use $rootScope for persistence
 across controllers
  9. the js (4) // Subscribe to the Channel! PubNub.ngSubscribe({ channel:

    $scope.channel }); • Subscribe to “The Angular Channel”
 channel • Enable AngularJS $broadcast events
 in the background for messages and
 presence events
  10. the js (5) // Create a publish() function in the

    scope! $scope.publish = function() {! PubNub.ngPublish({! channel: $scope.channel,! message: "[" + $scope.userId + "] " + $scope.newMessage! });! $scope.newMessage = '';! }; • Create a “publish()” function: • Call the PubNub ngPublish() method • Reset the ‘newMessage’ model
  11. the js (6) // Register for message events! $rootScope.$on(PubNub.ngMsgEv($scope.channel), function(ngEvent,

    payload) {! $scope.$apply(function() {! $scope.messages.push(payload.message);! });! }); • Register a callback for message events • Push the message into the messages list • Call within $scope.$apply so AngularJS knows about the change
  12. the js (7) // Register for presence events (optional)! $rootScope.$on(PubNub.ngPrsEv($scope.channel),


    function(ngEvent, payload) {! $scope.$apply(function() {! $scope.users = PubNub.ngListPresence($scope.channel);! });! }); • Register a callback for presence events • Get the list of users from the PubNub service • Update the users list in $scope • Call within $scope.$apply so AngularJS knows about the change
  13. the js (8) // Pre-Populate the user list (optional)! PubNub.ngHereNow({!

    channel: $scope.channel! });! ! // Populate message history (optional)! PubNub.ngHistory({! channel: $scope.channel,! count: 500! }); • Call the ngHereNow() function to trigger an initial presence event • Call the ngHistory() function to trigger historical message events
  14. interesting tidbits service vs. directive $rootScope vs. $scope events vs.

    callbacks wrap vs. raw internal bookkeeping promises vs. callbacks or return values