Skip to content

Instantly share code, notes, and snippets.

@grantglidewell
Last active April 7, 2020 17:08
Show Gist options
  • Save grantglidewell/4283e4dcd59e05f05269f42015d8d205 to your computer and use it in GitHub Desktop.
Save grantglidewell/4283e4dcd59e05f05269f42015d8d205 to your computer and use it in GitHub Desktop.
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