Chapter 5: Building an event bus
by billy roberts
HTML
<script src="https://code.angularjs.org/1.3.2/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="Ctrl">
<button ng-click="generateEvent()">Generate event</button>
</div>
<div my-dir></div>
</div>
JavaScript
//TOTALLY CLEAN PUB/SUB - implicitly add the pub/sub util to all
// scopes by decorating rootScope
angular.module('myApp',[])
.config(function($provide){
$provide.decorator('$rootScope', function($delegate){
// adds to the constructor prototype to allow use in isolate scopes
var proto = $delegate.constructor.prototype;
proto.subscribe = function(event, listener) {
var unsubscribe = $delegate.$on(event, listener);
this.$on('$destroy', unsubscribe);
};
proto.publish = function(event, data) {
$delegate.$emit(event, data);
};
return $delegate;
});
})
.controller('Ctrl',function($scope, $log) {
$scope.generateEvent = function() {
$scope.publish('busEvent');
};
$scope.subscribe('busEvent', function() {
$log.log('Handler called!');
});
})
.directive('myDir', function($log) {
return {
scope: {},
link: function(scope, el, attrs) {
scope.subscribe('busEvent', function() {
$log.log('Handler called!');
});
}
};
});