-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjsRoute.js
51 lines (42 loc) · 942 Bytes
/
jsRoute.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
/**
* Inspired by https://github.com/timotta/TralhaController
*/
var route = {
routes: [],
funcs: [],
currentHash: '',
interval: null,
add: function(route, func){
this.routes.push(route);
this.funcs.push(func);
},
init: function(){
if(!this.interval){
this.interval = setInterval( function() { route._check(); }, 400 );
}
},
_check: function() {
if( document.location.hash && this.currentHash != document.location.hash) {
this.currentHash = document.location.hash.slice(1);
this._update();
}
},
_findAndExecute: function(route){
for( var i = 0, l = this.routes.length; i < l; i++ ){
var re = new RegExp(this.routes[i]);
var match = route.match(re);
if(match){
this.funcs[i](match[0]);
return true;
}
}
return false;
},
_update: function(){
var hash = this.currentHash;
this._findAndExecute(hash);
},
call: function(route){
this._findAndExecute(route);
}
};