Created
October 15, 2011 22:02
-
-
Save fatihacet/1290216 to your computer and use it in GitHub Desktop.
Simple PubSub implementation with JavaScript - taken from Addy Osmani's design patterns book -
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
var pubsub = {}; | |
(function(q) { | |
var topics = {}, subUid = -1; | |
q.subscribe = function(topic, func) { | |
if (!topics[topic]) { | |
topics[topic] = []; | |
} | |
var token = (++subUid).toString(); | |
topics[topic].push({ | |
token: token, | |
func: func | |
}); | |
return token; | |
}; | |
q.publish = function(topic, args) { | |
if (!topics[topic]) { | |
return false; | |
} | |
setTimeout(function() { | |
var subscribers = topics[topic], | |
len = subscribers ? subscribers.length : 0; | |
while (len--) { | |
subscribers[len].func(topic, args); | |
} | |
}, 0); | |
return true; | |
}; | |
q.unsubscribe = function(token) { | |
for (var m in topics) { | |
if (topics[m]) { | |
for (var i = 0, j = topics[m].length; i < j; i++) { | |
if (topics[m][i].token === token) { | |
topics[m].splice(i, 1); | |
return token; | |
} | |
} | |
} | |
} | |
return false; | |
}; | |
}(pubsub)); |
This isn't publish subscribe pattern, this is the simplest observer pattern.
How can I use this as a subscriber
@scazzy thank you it's precisely what i needed
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
While above is good, and it's crazily 7 years old. I try below method. Instead of using an array, I use an object for each subscriptions as well. Simpler and smaller Also note the unsubscribe closure return in publish, kinda helps.
PubSub.js
Example