Skip to content

Instantly share code, notes, and snippets.

@bradleykronson
Created August 19, 2013 13:56
Show Gist options
  • Save bradleykronson/6269396 to your computer and use it in GitHub Desktop.
Save bradleykronson/6269396 to your computer and use it in GitHub Desktop.
Observer Pattern Wherever you see subscription or dispatching of events, you'll likely see this pattern. There are observers which are interested in something related to a specific object. Once the action occurs, the object notifies the observers. The example below shows how we can add an observer to the Users object:
var Users = {
list: [],
listeners: {},
add: function(name) {
this.list.push({name: name});
this.dispatch("user-added");
},
on: function(eventName, listener) {
if(!this.listeners[eventName]) this.listeners[eventName] = [];
this.listeners[eventName].push(listener);
},
dispatch: function(eventName) {
if(this.listeners[eventName]) {
for(var i=0; i<this.listeners[eventName].length; i++) {
this.listeners[eventName][i](this);
}
}
},
numOfAddedUsers: function() {
return this.list.length;
}
};
Users.on("user-added", function() {
alert(Users.numOfAddedUsers());
});
Users.add("Krasimir");
Users.add("Tsonev");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment