本文实例讲述了js实现简单路由器功能的方法。分享给大家供大家参考。具体实现方法如下:
var wawa = {};
wawa.router = function(){
function router(){
}
router.prototype.setup = function(routemap, defaultfunc){
var that = this, rule, func;
this.routemap = [];
this.defaultfunc = defaultfunc;
for (var rule in routemap) {
if (!routemap.hasownproperty(rule)) continue;
that.routemap.push({
rule: new regexp(rule, 'i'),
func: routemap[rule]
});
}
};
router.prototype.start = function(){
console.log(window.location.hash);
var hash = location.hash, route, matchresult;
for (var routeindex in this.routemap){
route = this.routemap[routeindex];
matchresult = hash.match(route.rule);
if (matchresult){
route.func.apply(window, matchresult.slice(1));
return;
}
}
this.defaultfunc();
};
return router;
}();
var router = new wawa.router();
router.setup({
'#/list/(.*)/(.*)': function(cate, id){
console.log('list', cate, id);
},
'#/show/(.*)': function(id){
console.log('show', id);
}
}, function(){
console.log('default router');
});
router.start();
希望本文所述对大家的javascript程序设计有所帮助。
更多js实现简单路由器功能的方法。