Created
June 22, 2016 21:29
-
-
Save alesanabriav/11a7cf3278d69749d969c1a4b5d64550 to your computer and use it in GitHub Desktop.
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
function observable(value) { | |
let listeners = []; | |
let notify = (newValue) => listeners.forEach((listener) => listener(newValue)); | |
function accessor(newValue) { | |
if(arguments.length && newValue !== value) { | |
value = newValue; | |
notify(newValue); | |
} | |
return value; | |
} | |
accessor.subscribe = (listener) => listeners.push(listener); | |
return accessor; | |
} | |
var n = observable(4); | |
n.subscribe( val => console.log('subscribe val: ' + val) ); | |
n.subscribe( val => console.log('subscribe again val: ' + val) ); | |
n(20); | |
n(25); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment