Skip to content

Instantly share code, notes, and snippets.

@ohvitorino
Forked from learncodeacademy/pubsub.js
Created May 6, 2016 12:06
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 ohvitorino/92b2c0fd7c600c71beb47e043d82a6c8 to your computer and use it in GitHub Desktop.
Save ohvitorino/92b2c0fd7c600c71beb47e043d82a6c8 to your computer and use it in GitHub Desktop.
Basic Javascript PubSub Pattern
//events - a super-basic Javascript (publish subscribe) pattern
var events = {
events: {},
on: function (eventName, fn) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(fn);
},
off: function(eventName, fn) {
if (this.events[eventName]) {
for (var i = 0; i < this.events[eventName].length; i++) {
if (this.events[eventName][i] === fn) {
this.events[eventName].splice(i, 1);
break;
}
};
}
},
emit: function (eventName, data) {
if (this.events[eventName]) {
this.events[eventName].forEach(function(fn) {
fn(data);
});
}
}
};
@ohvitorino
Copy link
Author

Other objects should be able to call:

events.on("eventName", eventHandlerFunction) to subscribe to an event
events.off("eventName") to unsubscribe
events.emit("eventName", data) to trigger the event and notify all the listeners

emit can be renamed to trigger

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