-
-
Notifications
You must be signed in to change notification settings - Fork 429
/
FluxStore.ts
54 lines (44 loc) · 1.31 KB
/
FluxStore.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { EventEmitter } from 'fbemitter';
import { Event } from '../dispatcher/AppDispatcher';
import * as Flux from "flux";
const CHANGE_EVENT = 'change';
class FluxStore<TState> {
private changed: boolean;
private emitter: EventEmitter;
private dispatchToken: string;
private dispatcher: Flux.Dispatcher<Event>;
private cleanStateFn: () => TState;
protected state: TState;
constructor(dispatcher: Flux.Dispatcher<Event>, public onDispatch: (action: Event) => void, cleanStateFn: () => TState) {
this.emitter = new EventEmitter();
this.changed = false;
this.dispatcher = dispatcher;
this.dispatchToken = dispatcher.register(payload => {
this.invokeOnDispatch(payload);
});
this.cleanStateFn = cleanStateFn;
this.state = this.cleanStateFn();
}
/**
* Is idempotent per dispatched event
*/
emitChange() {
this.changed = true;
}
hasChanged() { return this.changed; }
addChangeListener(callback: () => void) {
return this.emitter.addListener(CHANGE_EVENT, callback);
}
public cleanState() {
this.changed = false;
this.state = this.cleanStateFn();
}
private invokeOnDispatch(payload: Event) {
this.changed = false;
this.onDispatch(payload);
if (this.changed) {
this.emitter.emit(CHANGE_EVENT);
}
}
}
export default FluxStore;