Last active
April 7, 2020 17:08
-
-
Save grantglidewell/4283e4dcd59e05f05269f42015d8d205 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 initObservable() { | |
let observableData = []; | |
let observers = []; | |
const updateData = newData => { | |
observableData = newData; | |
updateObservers() | |
}; | |
const subscribe = obs => observers.push(obs); | |
const unsubscribe = f => (observers = observers.filter(obs => obs !== f)); | |
const add = data => { | |
updateData([ | |
...observableData, | |
{ | |
...data, | |
id: data.id || Date.now() + observableData.length | |
} | |
]); | |
}; | |
const remove = id => { | |
updateData(observableData.filter(not => not.id !== id)); | |
}; | |
const updateObservers = () => observers.forEach(obs => obs(observableData)); | |
return { | |
add, | |
remove, | |
subscribe, | |
unsubscribe | |
}; | |
} | |
const { | |
add, | |
remove, | |
subscribe, | |
unsubscribe | |
} = initObservable(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment