Last active
August 29, 2015 13:57
-
-
Save b-ma/9485420 to your computer and use it in GitHub Desktop.
small pubsub - (maybe `call` api would be better finally...)
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 cache = {}; | |
var pubsub = { | |
publish: function(channel, args) { | |
if (!cache[channel]) { | |
return; | |
} | |
var stack = cache[channel]; | |
for (var i = 0, l = stack.length; i < l; i++) { | |
var token = stack[i]; | |
token.callback.apply(token.ctx, args); | |
} | |
}, | |
subscribe: function(channel, callback, ctx) { | |
if (!cache[channel]) { | |
cache[channel] = []; | |
} | |
var token = { | |
channel: channel, | |
callback: callback, | |
ctx: (ctx || {}) | |
}; | |
cache[channel].push(token); | |
return token; | |
}, | |
unsubscribe: function(token) { | |
var stack = cache[token.channel]; | |
for (var i = 0, l = stack.length; i < l; i++) { | |
var cachedToken = stack[i]; | |
if ( | |
cachedToken.callback === token.callback && | |
cachedToken.ctx === token.ctx | |
) { | |
stack.splice(i, 1); | |
return; | |
} | |
} | |
}, | |
// @TODO : remove all handlers associated to the ctx | |
removeHandlers: function(ctx) {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment