-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathEnvironment.js
95 lines (80 loc) · 1.99 KB
/
Environment.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
"use strict";
// batchedUpdates is now exposed in 0.12
var batchedUpdates = require("react-dom").unstable_batchedUpdates || require('react').batchedUpdates;
/**
* Base abstract class for a routing environment.
*
* @private
*/
function Environment() {
this.routers = [];
this.path = this.getPath();
}
/**
* Notify routers about the change.
*
* @param {Object} navigation
* @param {Function} cb
*/
Environment.prototype.notify = function notify(navigation, cb) {
var latch = this.routers.length;
if (latch === 0) {
return cb && cb();
}
function callback() {
latch -= 1;
if (cb && latch === 0) {
cb();
}
}
batchedUpdates(function() {
for (var i = 0, len = this.routers.length; i < len; i++) {
this.routers[i].setPath(this.path, navigation, callback);
}
}.bind(this));
};
Environment.prototype.makeHref = function makeHref(path) {
return path;
};
Environment.prototype.navigate = function navigate(path, navigation, cb) {
return this.setPath(path, navigation, cb);
};
Environment.prototype.setPath = function(path, navigation, cb) {
// Support (path, cb) arity.
if (typeof navigation === 'function' && cb === undefined) {
cb = navigation;
navigation = {};
}
// Support (path) arity.
if (!navigation) navigation = {};
if (!navigation.isPopState) {
if (navigation.replace) {
this.replaceState(path, navigation);
} else {
this.pushState(path, navigation);
}
}
this.path = path;
this.notify(navigation, cb);
};
/**
* Register router with an environment.
*/
Environment.prototype.register = function register(router) {
if (this.routers.length === 0) {
this.start();
}
this.routers.push(router);
};
/**
* Unregister router from an environment.
*/
Environment.prototype.unregister = function unregister(router) {
if (this.routers.indexOf(router) > -1) {
this.routers.splice(this.routers.indexOf(router), 1);
}
if (this.routers.length === 0) {
this.stop();
}
};
module.exports = Environment;