Skip to content

Instantly share code, notes, and snippets.

@vojtajina
Created July 30, 2011 13:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vojtajina/1115537 to your computer and use it in GitHub Desktop.
Save vojtajina/1115537 to your computer and use it in GitHub Desktop.
Angular $eventBus
// pseudocode
angular.service('$eventBus', function() {
var listeners = {};
var mainBus = function(scope) {
return new ChildBus(mainBus, scope);
};
mainBus.emit = function(type) {
var args = Array.prototype.slice.call(arguments, 1);
// optimize for calls with 1 or 0 arguments - "apply" is expensive
forEach(listeners[type], function(listener) {
if (!args.length) listener();
else if (!args.length == 1) listener(args[0]);
else listener.apply(null, args);
});
};
mainBus.on = function(type, listener) {
// add to listeners
};
mainBus.remove = function(type, listener) {
// remove from listeners
};
mainBus.removeAll = function(type) {
if (type) listeners[type] = [];
else listeners = {};
};
return mainBus;
function ChildBus(main, scope) {
var localListeners = {};
if (scope) // register dispose to removeAll()
this.on = function(type, listener) {
main.on(type, listener);
// add to localListeners
};
this.emit = main.emit;
this.removeListener = function(type, listener) {
main.removeListener(type, listener);
// remove from localListeners
};
this.removeAll = function(type) {
// let's do bit more magic to make it linear rather than quadratic...
// the order of localListeners is the same as in listeners
// see http://jsperf.com/remove-all-items-from-array
};
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment