Skip to content

Instantly share code, notes, and snippets.

@alesanabriav
Created June 22, 2016 21:29
Show Gist options
  • Save alesanabriav/11a7cf3278d69749d969c1a4b5d64550 to your computer and use it in GitHub Desktop.
Save alesanabriav/11a7cf3278d69749d969c1a4b5d64550 to your computer and use it in GitHub Desktop.
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