Last active
December 18, 2015 01:48
-
-
Save rendro/5706386 to your computer and use it in GitHub Desktop.
JavaScript Pub-Sub
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
var pubsub = (function () { | |
'use strict'; | |
var observers = []; | |
return { | |
subscribe: function (events, listener) { | |
var event, i; | |
events = events.split(' '); | |
for (i in events) { | |
if (events.hasOwnProperty(i)) { | |
event = events[i]; | |
(observers[event] || (observers[event] = [])).push(listener); | |
} | |
} | |
}, | |
unsubscribe: function (event, listener) { | |
var value, key; | |
for ( | |
value = observers[event] || []; | |
listener && (key = value.indexOf(listener)) > -1; | |
) { | |
value.splice(key, 1); | |
} | |
observers[event] = listener ? value : []; | |
}, | |
publish: function (event) { | |
var args = Array.prototype.slice.call(arguments, 1); | |
for ( | |
var value = observers[event], key = 0; | |
value && key < value.length; | |
) { | |
value[key++].apply(this, args); | |
} | |
} | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment