Last active
October 7, 2016 08:39
-
-
Save JScott/cda54f715375a3ff294e to your computer and use it in GitHub Desktop.
Like David Walsh's pubsub object but better
This file contains hidden or 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
/* 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
depends on underscore || lodash ?