Created
January 2, 2012 22:22
-
-
Save adomokos/1552374 to your computer and use it in GitHub Desktop.
Observer in JavaScript
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 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