Advertisement
lidia_defreitas

Angular Observer Pattern

Nov 12th, 2016
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 5 1.69 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <title>Angular Observer Pattern</title>
  5. </head>
  6. <body>
  7.     <div ng-app="app">
  8.         <ul ng-controller="myController as vm">
  9.             <li ng-repeat="notification in vm.notifications">{{notification}}</li>
  10.         </ul>
  11.     </div>
  12.  
  13.     <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
  14.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
  15.  
  16.  
  17.     <script>
  18.         angular.module('app', []);
  19.  
  20.         angular.module('app').factory('Observer', Observer);
  21.  
  22.         function Observer() {
  23.             var _subscribers = [];
  24.  
  25.             setInterval(function () {
  26.                 console.log(_subscribers);
  27.                 angular.forEach(_subscribers, function (cb) {
  28.                     cb('something special @ ' + new Date());
  29.                 });
  30.             }, 2500);
  31.  
  32.             function subscribe(cb) {
  33.                 _subscribers.push(cb);
  34.             }
  35.  
  36.             return {
  37.                 subscribe: subscribe
  38.             };        
  39.         }
  40.  
  41.  
  42.         angular.module('app').controller('myController', myController);
  43.            
  44.         function myController($scope, Observer) {
  45.             var vm = this;    
  46.             var _stopWatchingSignIn = Observer.subscribe(notify);        
  47.             vm.notifications = ['nothing yet'];
  48.  
  49.             function notify(notification) {
  50.                 $scope.$apply(function () {
  51.                     vm.notifications.push('got ' + notification);
  52.                 });
  53.             }
  54.  
  55.             $scope.$on('$destroy', function (){
  56.                 _stopWatchingSignIn();
  57.             });
  58.         }
  59.  
  60.     </script>
  61. </body>
  62. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement