Skip to content

Instantly share code, notes, and snippets.

@JesusLeon
Forked from learncodeacademy/pubsub.js
Last active August 29, 2015 14:27
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 JesusLeon/2807fa24567c6f1328de to your computer and use it in GitHub Desktop.
Save JesusLeon/2807fa24567c6f1328de to your computer and use it in GitHub Desktop.
Basic Javascript PubSub Pattern
// Event - a super-basic Javascript (publish subscribe) pattern
var Event = {
event: {},
listen: function (eventName, fn) {
this.event[eventName] = this.event[eventName] || [];
this.event[eventName].push(fn);
},
forget: function(eventName, fn) {
if (this.event[eventName]) {
for (var i=0; i < this.event[eventName].length; i++) {
if (this.event[eventName][i] === fn) {
this.event[eventName].splice(i, 1);
break;
}
};
}
},
fire: function (eventName, data) {
if (this.event[eventName]) {
this.event[eventName].forEach(function(fn) {
fn(data);
});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment