Created
June 22, 2018 10:30
-
-
Save Farmatique/af18edf90d7f510b42de797c9c7486f4 to your computer and use it in GitHub Desktop.
Simple JS observer
This file contains hidden or 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
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