Created
August 19, 2013 13:56
-
-
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:
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 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