Skip to content

Instantly share code, notes, and snippets.

@sentient06
Created July 21, 2015 14:39
Show Gist options
  • Save sentient06/e6824f2a540ee14f4b38 to your computer and use it in GitHub Desktop.
Save sentient06/e6824f2a540ee14f4b38 to your computer and use it in GitHub Desktop.
Testing the observers concept in pure JavaScript
var EventManager = EventManager || {
handlers: {}
};
EventManager.subscribe = function(event, fn) {
if (typeof(this.handlers[event]) === 'undefined')
this.handlers[event] = [];
this.handlers[event].push(fn);
};
EventManager.unsubscribe = function(event, fn) {
this.handlers[event] = this.handlers[event].filter(
function(item) {
if (item !== fn) {
return item;
}
}
);
if (this.handlers[event].length === 0) {
console.log("Terminating event " + event);
delete this.handlers[event];
}
};
EventManager.publish = function(o, thisObj) {
var scope = thisObj || window;
if (typeof(this.handlers.book_published) === 'undefined') {
console.log(o + ' can\'t be published because there are no readers');
return;
}
this.handlers.book_published.forEach(function(item) {
item.call(scope, o);
});
};
// ----------------------------------------------
function Reader(name) {
this.name = name || "Anonymous reader";
console.log('New reader: ' + this.name);
var self = this;
var reaction = function(title) {
console.log(self.name + ' is reading '+ title);
};
this.subscribeToBooks = function() {
console.log(this.name + ' is subscribing to books');
EventManager.subscribe('book_published', reaction);
};
this.unsubscribeBooks = function() {
console.log(this.name + ' gave up reading');
EventManager.unsubscribe('book_published', reaction);
};
}
var james = new Reader('James');
var harry = new Reader('Harry');
var alice = new Reader('Alice');
james.subscribeToBooks();
EventManager.publish('Lord of the Rings');
harry.subscribeToBooks();
EventManager.publish('World of Narnia');
james.unsubscribeBooks();
EventManager.publish('The Picture of Dorian Grey');
james.subscribeToBooks();
EventManager.publish('The Silmarillion');
james.unsubscribeBooks();
harry.unsubscribeBooks();
EventManager.publish('Alice\'s Adventures in Wonderland');
alice.subscribeToBooks();
EventManager.publish('The Count of Monte Cristo');
alice.unsubscribeBooks();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment