Last active
May 2, 2017 14:27
-
-
Save sebringj/cd1a8200285c281938a9883df4aa7522 to your computer and use it in GitHub Desktop.
Tiny Flux Store for React
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 TinyStore { | |
constructor(key) { | |
this._events = {}; | |
this._data = undefined; | |
this._key = key; | |
} | |
on(evt, fn) { | |
let list = this._events[evt] = this._events[evt] || []; | |
for (let fnItem of list) | |
if (fnItem === fn) return; | |
list.push(fn); | |
} | |
off(evt, fn) { | |
let list = this._events[evt] = this._events[evt] || []; | |
for (let i = 0; i < list.length; i++) { | |
if (list[i] === fn) { | |
list.splice(i, 1); | |
return; | |
} | |
} | |
} | |
emit(ev) { | |
if (!this._events[ev]) return; | |
let list = this._events[ev] = this._events[ev] || []; | |
let args = Array.prototype.slice.call(arguments).slice(1); | |
for (let fnItem of list) | |
fnItem(...args); | |
} | |
allOff() { | |
this._events = {}; | |
} | |
get() { | |
return this._data; | |
} | |
change(data) { | |
this._data = data; | |
this.emit('change'); | |
} | |
} | |
export default Store; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment