Skip to content

Instantly share code, notes, and snippets.

@yortuc
Created January 30, 2018 10:20
Show Gist options
  • Save yortuc/92f48f58d435549ebaca7bd195641c8c to your computer and use it in GitHub Desktop.
Save yortuc/92f48f58d435549ebaca7bd195641c8c to your computer and use it in GitHub Desktop.
// observable
// like ko.observable with subsciption
function ob(val){
let lastVal = val;
let callbacks = [];
const accessor = function(setVal){
if(setVal){
lastVal = setVal;
callbacks.forEach(c=> c(setVal));
}
else {
return lastVal;
}
}
accessor.subscribe = function(callback){
callbacks.push(callback);
}
return accessor;
}
@yortuc
Copy link
Author

yortuc commented Jan 30, 2018

Usage

// create with initial value
const name = ob('evren')

// read current value 
const strName = name()

// set new value
name('yortuc')

// subscribe to changes
name.subscribe(newVal => console.log(`my new name is ${newVal}`))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment