Last active
May 6, 2024 15:49
-
-
Save liqiang372/47a987065947f3338c1a168b8ee473e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should line 10 be
var subscribers = this.events[event]
instead?