Forked from syaifulsz/ssz_data_manager_observer.js
Last active
January 20, 2020 23:51
-
-
Save imranismail/5ecf41009d83d3e2629f98ac67816579 to your computer and use it in GitHub Desktop.
Simple ES Javascript Plugin for Data Manager & Observer (Single state of truth)
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
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