forked from aksonov/react-native-router-flux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Actions.js
105 lines (93 loc) · 3.01 KB
/
Actions.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import Route from './Route';
import Router from './Router';
import debug from './debug';
function isNumeric(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}
function filterParam(data){
if (data.toString()!='[object Object]')
return data;
if (!data){
return;
}
var proto = (data||{}).constructor.name;
// avoid passing React Native parameters
if (proto != 'Object'){
data = {};
}
if (data.data){
data.data = filterParam(data.data);
}
return data;
}
class Actions {
currentRouter: ?Router;
constructor(){
this.pop = this.pop.bind(this);
this.route = this.route.bind(this);
}
route(name: string, props: { [key: string]: any} = {}){
if (!this.currentRouter){
throw new Error("No current router is set");
}
if (props.toString()!='[object Object]')
props = {data : props};
props = filterParam(props);
// check if route is in children, current or parent routers
let router: Router = this.currentRouter;
// deep into child router
while (router.currentRoute.childRouter){
router = router.currentRoute.childRouter;
debug("Switching to child router="+router.name);
}
debug("Route to "+name+" current router="+this.currentRouter.name+ " current route="+this.currentRouter.currentRoute.name);
while (!router.routes[name]){
const route = router.parentRoute;
if (!route || !route.parent){
throw new Error("Cannot find router for route="+name+" current router="+router.name);
}
router = route.parent;
debug("Switching to router="+router.name);
}
if (router.route(name, props)){
// deep into child router
while (router.currentRoute.childRouter){
router = router.currentRoute.childRouter;
debug("Switching to child router="+router.name);
}
this.currentRouter = router;
return true;
}
return false;
}
pop(num: number = 1){
if (!isNumeric(num)){
num = 1;
}
if (!this.currentRouter){
throw new Error("No current router is set");
}
if (num > 1){
for (let i=0;i<num;i++){
if (!Actions.pop()){
return false;
}
}
return true;
} else {
let router: Router = this.currentRouter;
debug("Pop, router="+router.name);
while (router.stack.length <= 1 || router.currentRoute.type === 'switch'){
router = router.parentRoute.parent;
debug("Switching to parent router="+router.name);
}
if (router.pop()){
this.currentRouter = router;
return true;
} else {
return false;
}
}
}
}
export default new Actions();