Here is a simple observer (subscriber/publisher) patter implemented in JavaScript using the module patter.
// Observer class.
var observer = function(){
// Maintain list of subscribes.
var subscribers = {};
return {
subscribe: function(obj){
subscribers[obj.id] = obj.fn;
},
publish: function(obj){
// Loop through all subscribers.
for (var key in subscribers) {
subscribers[key](obj);
}
},
unsubscribe: function(id){
delete subscribers[id];
}
};
};
var instance = observer();
// Subscribe foo.
instance.subscribe({
id: 'foo',
fn: function(obj){
console.log('foo got message')
console.log(obj)
}
});
// Subscribe bar.
instance.subscribe({
id: 'bar',
fn: function(obj){
console.log('bar got message')
console.log(obj)
}
});
// Publish to foo and bar.
instance.publish({message: 'hi dave'});
// Unsubscribe foo.
instance.unsubscribe('foo');
If you prefer "classical" aproach through prototypal inheritance, Dustin Diaz in his blog post suggest this approach:
function Observer() {
this.fns = [];
}
Observer.prototype = {
subscribe: function (fn) {
this.fns.push(fn);
},
unsubscribe: function (fn) {
this.fns = this.fns.filter(
function (el) {
if (el !== fn) {
return el;
}
}
);
},
fire: function (o, thisObj) {
var scope = thisObj || window;
this.fns.forEach(
function (el) {
el.call(scope, o);
}
);
}
};