Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save imranismail/5ecf41009d83d3e2629f98ac67816579 to your computer and use it in GitHub Desktop.
Save imranismail/5ecf41009d83d3e2629f98ac67816579 to your computer and use it in GitHub Desktop.
Simple ES Javascript Plugin for Data Manager & Observer (Single state of truth)
class DataManager {
_listeners = [];
constructor(initialData) {
this._data = initialData;
}
dispatch = (data) => {
this._data = data;
for (let listener of this._listeners) {
listener(data)
}
}
get data() {
return this._data;
}
subscribe(callback) {
this._listeners.push(callback);
let from = this._listeners.length - 1;
return () => {
this._listeners.splice(from, 1)
}
}
}
let dataMgr = new DataManager({});
let unsubscribe = dataMgr.subscribe((data) => {
console.log(data)
})
setInterval(() => {
dataMgr.dispatch("This is a plain old message, there are many in this world, but this is mine")
}, 1000)
setTimeout(() => {
unsubscribe()
}, 5000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment