Skip to content

Instantly share code, notes, and snippets.

@jcarley
Created July 27, 2013 18:01
Show Gist options
  • Save jcarley/6095710 to your computer and use it in GitHub Desktop.
Save jcarley/6095710 to your computer and use it in GitHub Desktop.
Demonstrates an even aggregator with Angular.js. See http://jsfiddle.net/XqDxG/452/ for a working example. Initial code taken from https://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js
var myModule = angular.module('myModule', []);
myModule.factory('eventAggregator', function() {
var cache = {};
return {
publish: function(topic, args) {
cache[topic] && $.each(cache[topic], function(func) {
this.apply(null, args || []);
});
},
subscribe: function(topic, callback) {
if(!cache[topic]) {
cache[topic] = [];
}
cache[topic].push(callback);
return [topic, callback];
},
unsubscribe: function(handle) {
var t = handle[0];
cache[t] && $.each(cache[t], function(idx){
if(this == handle[1]){
cache[t].splice(idx, 1);
}
});
}
}
});
function ControllerZero($scope, eventAggregator) {
$scope.message = 'cat.mov';
$scope.handleFileUploadClick = function(msg) {
eventAggregator.publish("FileUploaded", [msg]);
};
$scope.handleFileDeletedClick = function(msg) {
eventAggregator.publish("FileDeleted", [msg]);
};
}
function ControllerOne($scope, eventAggregator) {
eventAggregator.subscribe("FileUploaded", function(msg) {
$scope.message = 'Uploaded: ' + msg;
});
}
function ControllerTwo($scope, eventAggregator) {
eventAggregator.subscribe("FileDeleted", function(msg) {
$scope.message = 'Deleted: ' + msg;
});
}
ControllerZero.$inject = ['$scope', 'eventAggregator'];
ControllerOne.$inject = ['$scope', 'eventAggregator'];
ControllerTwo.$inject = ['$scope', 'eventAggregator'];
<div ng-controller="ControllerZero">
<input ng-model="message">
<button ng-click="handleFileUploadClick(message);">Upload</button>
<button ng-click="handleFileDeletedClick(message);">Delete</button>
</div>
<div ng-controller="ControllerOne">
<input ng-model="message" >
</div>
<div ng-controller="ControllerTwo">
<input ng-model="message" >
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment