简单路由器实现附带详细说明

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;

// 知识点:hasOwnProperty 这个怎么用?

that.routemap.push({

rule: new RegExp(rule, 'i'),

func: routemap[rule] // 路由函数

});

}

};

Router.prototype.start = function(){

console.log(window.location.hash);

// 知识点:location.hash --- 监听浏览器的 hash 改变 ie8 版本为分割点 关于 onhashchange 的实现(原谅我不分大小写)

var hash = location.hash, route, matchResult;

for (var routeIndex in this.routemap){

route = this.routemap[routeIndex];

matchResult = hash.match(route.rule);

// 知识点:match 返回的是一个还是多个

if (matchResult){

route.func.apply(window, matchResult.slice(1));

// call 和 apply 的区别 关于改变函数 this 的事 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();

以上是 简单路由器实现附带详细说明 的全部内容, 来源链接: utcz.com/z/264805.html

回到顶部