forked from vjau/reactive-redux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
62 lines (52 loc) · 1.52 KB
/
index.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 {get as pathGet} from 'object-path';
import initSubscriber from "redux-subscriber";
import {Tracker} from "meteor/tracker";
const watchSelector = (selector, Store, cb)=>{
let prevComputedState = selector(Store.getState());
const compare = (newState)=>{
let newComputedState = selector(newState);
if (prevComputedState !== newComputedState){
prevComputedState = newComputedState;
cb();
}
};
return Store.subscribe(()=>(compare(Store.getState())));
};
let subscriber;
const factory = (pathOrSelector, Store)=>{
if (typeof pathOrSelector !== "string" && typeof pathOrSelector !== "function"){
throw new Error("factory pathOrSelector should be a string or a function");
}
if (!Store || typeof Store.getState !== "function"){
throw new Error("factory should be provided with a Store");
}
if (!subscriber){
subscriber = initSubscriber(Store);
}
const dep = new Tracker.Dependency();
if (typeof pathOrSelector === "string"){
const unsubscribe = subscriber(pathOrSelector, ()=>(dep.changed()));
return {
get(){
dep.depend();
return pathGet(Store.getState(), pathOrSelector);
},
cancel(){
unsubscribe();
}
}
}
if (typeof pathOrSelector === "function"){
const unsubscribe = watchSelector(pathOrSelector, Store, ()=>(dep.changed()));
return {
get(){
dep.depend();
return pathOrSelector(Store.getState());
},
cancel(){
unsubscribe();
}
}
}
};
export default factory;