Skip to content

Instantly share code, notes, and snippets.

@LucasReade
Created May 26, 2020 08:02
Show Gist options
  • Save LucasReade/e6b90c519111646dff65d31b682354c2 to your computer and use it in GitHub Desktop.
Save LucasReade/e6b90c519111646dff65d31b682354c2 to your computer and use it in GitHub Desktop.
Basic javascript observable
function Observable(initialVal = undefined) {
let staticValue = initialVal;
let listeners = [];
this.next = (val) => {
staticValue = val;
listeners.forEach(cb => cb(val));
}
this.subscribe = (listener) => {
if(typeof listener === 'function') {
listeners.push(listener);
}
}
this.unSubscribe = (listener) => {
let listenerIdx = listeners.findIndex(cb => cb === listener);
listeners.splice(listenerIdx, 1);
}
}
@LucasReade
Copy link
Author

Basic JavaScript observable. Create by calling the following code
const count = new Observable(0);

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