Skip to content

Instantly share code, notes, and snippets.

@JScott
Last active October 7, 2016 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JScott/cda54f715375a3ff294e to your computer and use it in GitHub Desktop.
Save JScott/cda54f715375a3ff294e to your computer and use it in GitHub Desktop.
Like David Walsh's pubsub object but better
/* Improved from http://davidwalsh.name/pubsub-javascript
- Improved readability
- Friendlier naming conventions
- Generic data for publishing
*/
var event: (function(){
var topic = {};
return {
subscribe: function(name, listener) {
if ( _.isUndefined(topic[name]) ) {
topic[name] = { queue: [] };
}
var index = topic[name].queue.push(listener) - 1;
return {
remove: function() {
delete topic[name].queue[index];
}
};
},
publish: function(name, data) {
if(_.isUndefined(topic[name]) || topic[name].queue.length == 0) {
return;
}
topic[name].queue.forEach(function(callback) {
callback(data || null);
});
}
};
})()
// Example usage
var subscription = event.subscrube('test', function(string) { alert(string); });
event.publish('test', 'hi!');
event.publish('test');
subscription.remove();
@Pushplaybang
Copy link

depends on underscore || lodash ?

@martisj
Copy link

martisj commented Oct 7, 2016

Do you use this @JScott ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment