-
-
Notifications
You must be signed in to change notification settings - Fork 15.2k
/
Copy pathRedux.js
62 lines (52 loc) · 1.43 KB
/
Redux.js
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
55
56
57
58
59
60
61
62
import createDispatcher from './createDispatcher';
import composeStores from './utils/composeStores';
import thunkMiddleware from './middleware/thunk';
import identity from 'lodash/utility/identity';
export default class Redux {
constructor(dispatcher, initialState, prepareState = identity) {
if (typeof dispatcher === 'object') {
// A shortcut notation to use the default dispatcher
dispatcher = createDispatcher(
composeStores(dispatcher),
getState => [thunkMiddleware(getState)]
);
}
this.state = initialState;
this.prepareState = prepareState;
this.listeners = [];
this.replaceDispatcher(dispatcher);
}
getDispatcher() {
return this.dispatcher;
}
replaceDispatcher(nextDispatcher) {
this.dispatcher = nextDispatcher;
this.dispatchFn = nextDispatcher({
getState: ::this.getRawState,
setState: ::this.setState
});
this.dispatch({});
}
dispatch(action) {
return this.dispatchFn(action);
}
getRawState() {
return this.state;
}
getState() {
return this.prepareState(this.state);
}
setState(nextState) {
this.state = nextState;
this.listeners.forEach(listener => listener());
return nextState;
}
subscribe(listener) {
const { listeners } = this;
listeners.push(listener);
return function unsubscribe () {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
}