Skip to content

Instantly share code, notes, and snippets.

@lsauvaget
Created June 1, 2015 15:20
Show Gist options
  • Save lsauvaget/341e541eff6aaa934513 to your computer and use it in GitHub Desktop.
Save lsauvaget/341e541eff6aaa934513 to your computer and use it in GitHub Desktop.
Publish-Subscribe Vanilla JS
//Fork of https://github.com/shichuan/javascript-patterns/blob/master/jquery-patterns/pubsub-plugin.html
// No need JQuery
var o = {};
(function(d){
// the topic/subscription hash
var cache = {};
d.publish = function(/* String */topic, /* Array? */args){
cache[topic] && [].forEach.call(cache[topic], function(element){
element.apply(d, args || []);
});
};
d.subscribe = function(/* String */topic, /* Function */callback){
if(!cache[topic]){
cache[topic] = [];
}
cache[topic].push(callback);
return [topic, callback]; // Array
};
// Disconnect a subscribed function for a topic.
d.unsubscribe = function(/* Array */handle){
// handle: Array - The return value from a $.subscribe call.
var t = handle[0];
cache[t] && [].forEach.call(cache[t], function(element,idx){
if(element == handle[1]){
cache[t].splice(idx, 1);
}
});
};
})(o);
var event = o.subscribe('test', function(){console.log('test');});
o.publish('test');
o.unsubscribe(event);
o.publish('test');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment