Created
March 29, 2018 09:55
-
-
Save RANUX/1e1fbdac982a58f6a3a952ac543c5d6b to your computer and use it in GitHub Desktop.
Simple JS Observer pattern
This file contains hidden or 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
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