-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathnavigation.js
53 lines (53 loc) · 1.41 KB
/
navigation.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
define(['dojo/when'], function(when){
// a navigation binding, that can receive and trigger data through the binding to control
// the navigation history
var navigation = function(target, options){
// provide a store and a prefix
options = options || {};
var store = options.store;
var prefix = options.prefix || '';
var usePushState = options.usePushState;
var currentPath;
// listen for changes in the data
target.receive(function(object){
var id = store.getIdentity(object);
if(id !== undefined){
currentPath = prefix + id;
if(usePushState){
if(location.pathname != currentPath){
location.pushState(currentPath);
}
}else{
if(location.hash != currentPath){
location.hash = currentPath;
}
}
}
});
// listen for changes in the hash
addEventListener('hashchange', update, false);
// do it at the beginning too
update();
function update(){
// in response to URL change or startup
var path = usePushState ?
location.pathname :
location.hash;
if(path.charAt(0) == '#'){
navigation.path = path = path.slice(1);
}
if(currentPath != path){
// only change if it matches or accepted prefixes
if(path.slice(0, prefix.length) == prefix){
when(store.get(path.slice(prefix.length)), function(object){
if(object){
target.put(object);
}
});
}
}
}
return target;
};
return navigation;
});