Created
May 26, 2020 08:02
-
-
Save LucasReade/e6b90c519111646dff65d31b682354c2 to your computer and use it in GitHub Desktop.
Basic javascript observable
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(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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Basic JavaScript observable. Create by calling the following code
const count = new Observable(0);