-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpushStrategy.js
51 lines (45 loc) · 1.08 KB
/
pushStrategy.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
var onChange = function () {};
var pushStrategy = {
init: function( options ){
this.basePath = options.basePath || '';
if( this.basePath.slice(-1) === '/' ){
this.basePath = this.basePath.slice(0, -1);
}
},
start: function(){
var me = this;
// Register event listener
window.onpopstate = function(){
me.emit();
};
// Emit first onChange
me.emit();
},
push: function( location ){
history.pushState( {}, '', this.basePath + location );
this.emit();
},
replace: function( location ){
history.replaceState( {}, '', this.basePath + location );
this.emit();
},
onChange: function( cb ){
onChange = cb;
},
getLocation: function(){
var l = location.pathname + location.search + location.hash,
basePathLength = this.basePath.length
;
if( l.slice(0, basePathLength) === this.basePath ){
l = l.slice( basePathLength );
}
return l;
},
emit: function(){
onChange && onChange( this.getLocation() );
},
back: function () {
window.history.back();
}
};
module.exports = pushStrategy;