Zero to Real-Time AngularJS in 60 Seconds

Ac1a1d449af259bfb7191105db5212a2?s=47 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.

Ac1a1d449af259bfb7191105db5212a2?s=128

Sunny Gleason

September 03, 2014
Tweet

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. take these… Codepen (single) http://goo.gl/rPwPcv Codepen (sectional) http://goo.gl/z8Sof5 Blog Entry

    http://goo.gl/rGOXGm PubNub Trial http://goo.gl/oJnTpv
  4. hello codepen (this is the 60 seconds part)

  5. why is real-time important?

  6. why is real-time important?

  7. applications should must be 
 customer-focused 
 responsive Ǎ 


    live updating
  8. our demo application real-time chat user presence  message history


    
 … in 99 lines of HTML/JS
  9. 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
  10. what does it do?

  11. 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)
  12. the html (2) <div class="container"
 ng-app="PubNubAngularApp"
 ng-controller="ChatCtrl">! ...! </div> •

    Configure Application • Bind the Controller
  13. the html (3) <h4>Online Users</h4>! <ul>! <li ng-repeat="user in users">{{user}}</li>!

    </ul> • Display a dynamic list of users
  14. 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()’
  15. the html (5) <div class="well">! <ul>! <li ng-repeat="message in messages">{{message}}</li>!

    </ul>! </div> • Display a dynamic list of messages
  16. 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
  17. 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
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. 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
  24. … and you’re done! questions? thank you!

  25. interesting tidbits service vs. directive $rootScope vs. $scope events vs.

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