Skip to content

Instantly share code, notes, and snippets.

@liqiang372
Last active May 6, 2024 15:49
Show Gist options
  • Save liqiang372/47a987065947f3338c1a168b8ee473e0 to your computer and use it in GitHub Desktop.
Save liqiang372/47a987065947f3338c1a168b8ee473e0 to your computer and use it in GitHub Desktop.
function Pubsub() {
this.events = {};
}
Pubsub.prototype.publish = function(event, args) {
if (!this.events[event]) {
return false;
}
var subscribers = this.events[event];
var len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len]();
}
return this;
}
Pubsub.prototype.subscribe = function(event, func) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(func);
}
Pubsub.prototype.unsubscribe = function(event, func) {
var self = this;
if (this.events[event]) {
this.events[event].forEach(function(el, index){
if (el == func) {
self.events.splice(index, 1);
}
})
}
}
var pubsub = new Pubsub();
var eat = function() {
console.log("I am eating");
}
var drink = function() {
console.log("I am drinking");
}
var running = function() {
console.log("I am running");
}
pubsub.subscribe("dinner", eat);
pubsub.subscribe("dinner", drink);
pubsub.subscribe("sports", running);
pubsub.publish("dinner");
// should log
// I am drinking
// I am eating
pubsub.publish("sports")
// should log
// I am running
@junshengpierre
Copy link

Should line 10 be var subscribers = this.events[event] instead?

@liqiang372
Copy link
Author

@junshengpierre Yes, it is. Already changed it. Thank you

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