js路由—简单路由的实现

路由是什么,其实就是引路人。。

先看一个简单的路由的实现。

路由就是根据不同的url请求,导航到不同的页面。

这里js的路由其实是根据不同的url请求,执行不同的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]
            });             
        }
    };                    

配置文件设置好了,在看下如果地址中有hash,并且hash能匹配到路由配置,

那就执行对应的函数,并且把匹配传递给函数

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();
    };

这个如果在同一个页面中跳转,函数是不执行的,直接从浏览器地址栏输入,对应的函数才可以执行。 后续看下backbone的路由的实现

原文地址:https://www.cnblogs.com/jingwensophie/p/4863784.html