Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Farmatique/af18edf90d7f510b42de797c9c7486f4 to your computer and use it in GitHub Desktop.
Save Farmatique/af18edf90d7f510b42de797c9c7486f4 to your computer and use it in GitHub Desktop.
Simple JS observer
function Observable() {
var observers = [];
this.sendMessage = function(msg){
for(var i = 0, length = observers.length; i < length; i++){
observers[i].notify(msg)
}
}
this.addObserver = function(observer){
observers.push(observer)
}
}
function Observer(behavior){
this.notify = function(msg){
behavior(msg)
}
}
var observable = new Observable();
var obs1 = new Observer(function(msg){console.log('fire first: '+msg)});
var obs2 = new Observer(function(msg){console.log('fire second: '+msg)});
observable.addObserver(obs1);
observable.addObserver(obs2);
observable.sendMessage('hello!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment