-
-
Save bboy114crew/4c7e30f3a4766c5835ed036fb145272d to your computer and use it in GitHub Desktop.
This file contains hidden or 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