Skip to content

Instantly share code, notes, and snippets.

@mrvicadai
Forked from minwe/simple-pubsub.es6.js
Created December 19, 2016 19:50
Show Gist options
  • Save mrvicadai/acdf3429f45989e2e851924348ba5532 to your computer and use it in GitHub Desktop.
Save mrvicadai/acdf3429f45989e2e851924348ba5532 to your computer and use it in GitHub Desktop.
class PubSub {
constructor() {
this.handlers = [];
}
subscribe(event, handler, context) {
if (typeof context === 'undefined') {
context = handler;
}
this.handlers.push({event: event, handler: handler.bind(context)});
}
publish(event) {
for (let i = 0; i < this.handlers.length; i++) {
if (this.handlers[i].event === event) {
this.handlers[i].handler.call();
}
}
}
}
var PubSub = function() {
this.handlers = [];
};
PubSub.prototype = {
constructor: PubSub,
subscribe: function(event, handler, context) {
if (typeof context === 'undefined') {
context = handler;
}
this.handlers.push({event: event, handler: handler.bind(context)});
},
publish: function(event) {
for (var i = 0; i < this.handlers.length; i++) {
if (this.handlers[i].event === event) {
this.handlers[i].handler.call();
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment