Skip to content

Instantly share code, notes, and snippets.

@wghglory
Created April 29, 2017 06:15
Show Gist options
  • Save wghglory/5380e73db629eb18e82da11f22429aa6 to your computer and use it in GitHub Desktop.
Save wghglory/5380e73db629eb18e82da11f22429aa6 to your computer and use it in GitHub Desktop.
publish subscribe 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);
});
}
}
};
// class Event {
// constructor() {
// this.events = {};
// }
//
// on(eventName, fn) {
// this.events[eventName] = this.events[eventName] || [];
// this.events[eventName].push(fn);
// }
//
// off(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(eventName, data) {
// if (this.events[eventName]) {
// this.events[eventName].forEach(function(fn) {
// fn(data);
// });
// }
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment