Skip to content

Instantly share code, notes, and snippets.

@sean-roberts
Last active December 25, 2015 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sean-roberts/7018909 to your computer and use it in GitHub Desktop.
Save sean-roberts/7018909 to your computer and use it in GitHub Desktop.
PublishSubscriberPattern Implementation - basic
// test gist http://jsfiddle.net/fJPkr/1/
var handler = {};
(function(h){
//holds the topics
var topics = {},
subUid = 0;
h.publish = function(topic, args){
//only publish topics that were subscribed to
if(!topics[topic]){
return false;
}
var subs = topics[topic],
len = subs ? subs.length : 0;
while(len--){
subs[len].func(topic, args)
}
//enable chaining
return this;
};
h.subscribe = function( topic, func ){
if(!topics[topic]){
topics[topic] = [];
}
var token = ( ++subUid ).toString();
topics[topic].push({
token : token,
func : func
});
return token;
};
h.unsubscribe = function(token){
for(var m in topics){
if(topics[m]){
for(var i = 0; i < topics[m].length; i++){
if(topics[m][i].token === token){
//remove this subscription from the topics
topics[m].splice(i, 1);
return token;
}
}
}
}
return this;
};
})(handler);
console.log(handler);
var subscriptionToken = handler.subscribe('test/sub', function(){
console.log('publish called');
});
handler.publish('test/sub');
handler.publish('test/sub');
handler.unsubscribe(subscriptionToken);
handler.publish('test/sub');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment