Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@adomokos
Created January 2, 2012 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adomokos/1552374 to your computer and use it in GitHub Desktop.
Save adomokos/1552374 to your computer and use it in GitHub Desktop.
Observer in JavaScript
var observer = {
addSubscriber: function(callback) {
this.subscribers[this.subscribers.length] = callback;
},
removeSubscriber: function(callback) {
for (var i = 0; i < this.subscribers.length; i++) {
if (this.subscribers[i] === callback) {
delete (this.subscribers[i]);
}
}
},
publish: function(what) {
for (var i = 0; i < this.subscribers.length; i++) {
if (typeof this.subscribers[i] === 'function') {
this.subscribers[i](what);
}
}
},
make: function(o) { // turns an object into a publisher
for (var i in this) {
o[i] = this[i];
o.subscribers = [];
}
}
};
var blogger = {
writeBlogPost: function() {
var content = 'Today is ' + new Date();
this.publish(content);
}
};
var la_times = {
newIssue: function() {
var paper = 'Martians have landed on Earth!';
this.publish(paper);
}
};
// Turning them into publishers
observer.make(blogger);
observer.make(la_times);
var jack = {
read: function(what) {
console.log('I just read that ' + what);
}
};
var jill = {
gossip: function(what) {
console.log('You didn\'t hear it from me, but ' + what);
}
};
blogger.addSubscriber(jack.read);
blogger.addSubscriber(jill.gossip);
blogger.writeBlogPost();
console.log('.... removing a subscriber');
blogger.removeSubscriber(jill.gossip);
blogger.writeBlogPost();
console.log('... try the la_times publisher');
la_times.addSubscriber(jill.gossip);
la_times.newIssue();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment