Pajax-2

路由的实现

(function() {

    var routes = [];
        
    //this will push the new route onto the 
    //list of routes.
    function addRoute(route, callback, scope){
        
        //create a consistent signature that 
        //we can rely on later
        var routeObj = {
            route: route,
            callback: callback,
            scope: scope
        };
        
        routes.push(routeObj);
    }
    
    //looks for matching routes, then calls the callback
    function handleRoute(path, noHistory) {
        
        var len = routes.length, scope;
        
        for (var i=0; i < len; i++) {
            if(path.match(routes[i].route)) {
                
                //if the caller provided a scope,
                //we use it, otherwise we will execute
                //the callback in the window scope
                if(routes[i].scope) {
                    scope = routes[i].scope;
                } else {
                    scope = window;
                }
                
                // if this is from a popstate,
                // we shouldn't push state again
                if(!noHistory) {
                    history.pushState({}, null, path);
                }
                
                //push the path onto the history stack
                routes[i].callback.apply(scope, [path]);
                return true;
            }
        }
        //no route found, move on
        return false;
    }
    
    window.addEventListener('popstate', function(e) {

        handleRoute(window.location.href, true);
    });
    
    window.router = {
        handleRoute:handleRoute,
        addRoute: addRoute
    };
    
})();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第二章 物理层 频分复用:频分复用的用户在同样的时间占用不同的带宽资源(频率带宽) 时分复用:时分复用的用户在不同...
    PramaWells阅读 9,294评论 1 3
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,734评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,791评论 25 709
  • 终于要去儿子心心念了好久的迪斯尼,去之前就听很多朋友说那边人很多,排队很久。听的我们都是心慌慌的,但玩好以...
    迷酒阅读 3,658评论 1 2
  • 时间的风 为你我披沙拣金 张手抚下 癫醉的黄叶 不知这是什么世界 庄严的他不敢抬头 开口大笑 窥不及合不合时宜 只...
    我的猫叫老板娘阅读 3,775评论 7 8