Skip to content

Instantly share code, notes, and snippets.

@RANUX
Created March 29, 2018 09:55
Show Gist options
  • Save RANUX/1e1fbdac982a58f6a3a952ac543c5d6b to your computer and use it in GitHub Desktop.
Save RANUX/1e1fbdac982a58f6a3a952ac543c5d6b to your computer and use it in GitHub Desktop.
Simple JS Observer pattern
let store = {
nextId: 1,
cache: {},
add(fn) {
if(!fn.id) {
fn.id = this.nextId++;
this.cache[fn.id] = fn;
}
return false;
},
runAll() {
for (let i=1; i < this.nextId; i++) {
this.cache[i]();
}
}
}
let func = () => console.log('test')
store.add(func)
store.add(func) // will not be re-added
store.add(() => console.log('test 2'))
store.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment