Created
July 30, 2011 13:41
-
-
Save vojtajina/1115537 to your computer and use it in GitHub Desktop.
Angular $eventBus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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