forked from twilson63/mercury-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.js
49 lines (36 loc) · 999 Bytes
/
router.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
'use strict';
var value = require('observ');
var source = require('geval/source');
var window = require('global/window');
var document = require('global/document');
var atom = router.atom = value(String(document.location.href));
function router() {
var inPopState = false;
var popstates = popstate();
popstates(onPopState);
atom(onRouteSet);
return { state: atom };
function onPopState(uri) {
inPopState = true;
atom.set(uri);
}
function onRouteSet(uri) {
if (inPopState) {
inPopState = false;
return;
}
pushHistoryState(uri);
}
}
function pushHistoryState(uri) {
window.history.pushState(null, document.title, uri);
}
function popstate() {
return source(function broadcaster(broadcast) {
window.addEventListener('popstate', onPopState);
function onPopState() {
broadcast(String(document.location.href));
}
});
}
module.exports = router;