freifunkmanager/js/helper/router.js

87 lines
2.3 KiB
JavaScript
Raw Normal View History

2016-07-01 08:25:32 +02:00
define(function(){
return {
routes: [],
mode: null,
root: '/',
config: function(options) {
2016-07-01 16:01:28 +02:00
this.mode = options && options.mode && options.mode == 'history' && !!(history.pushState) ? 'history' : 'hash';
2016-07-01 08:25:32 +02:00
this.root = options && options.root ? '/' + this.clearSlashes(options.root) + '/' : '/';
return this;
},
getFragment: function() {
var fragment = '';
if(this.mode === 'history') {
fragment = this.clearSlashes(decodeURI(location.pathname + location.search));
fragment = fragment.replace(/\?(.*)$/, '');
fragment = this.root != '/' ? fragment.replace(this.root, '') : fragment;
} else {
var match = window.location.href.match(/#(.*)$/);
fragment = match ? match[1] : '';
}
return this.clearSlashes(fragment);
},
clearSlashes: function(path) {
return path.toString().replace(/\/$/, '').replace(/^\//, '');
},
add: function(re, handler) {
if(typeof re == 'function') {
handler = re;
re = '';
}
this.routes.push({ re: re, handler: handler});
return this;
},
remove: function(param) {
2016-07-01 16:01:28 +02:00
var r;
for(var i=0; i<this.routes.length; i++) {
r = this.routes[i];
2016-07-01 08:25:32 +02:00
if(r.handler === param || r.re.toString() === param.toString()) {
this.routes.splice(i, 1);
return this;
}
}
return this;
},
flush: function() {
this.routes = [];
this.mode = null;
this.root = '/';
return this;
},
check: function(f) {
var fragment = f || this.getFragment();
for(var i=0; i<this.routes.length; i++) {
var match = fragment.match(this.routes[i].re);
if(match) {
match.shift();
this.routes[i].handler.apply({}, match);
return this;
}
}
return this;
},
listen: function() {
var self = this;
var current = self.getFragment();
var fn = function() {
if(current !== self.getFragment()) {
current = self.getFragment();
self.check(current);
}
2016-07-01 16:01:28 +02:00
};
2016-07-01 08:25:32 +02:00
clearInterval(this.interval);
this.interval = setInterval(fn, 50);
return this;
},
navigate: function(path) {
path = path ? path : '';
if(this.mode === 'history') {
history.pushState(null, null, this.root + this.clearSlashes(path));
} else {
window.location.href = window.location.href.replace(/#(.*)$/, '') + '#' + path;
}
return this;
}
};
2016-07-01 16:01:28 +02:00
});