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閱讀 3,825評論 1 3
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,915評論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,243評論 25 708
  • 終于要去兒子心心念了好久的迪斯尼,去之前就聽很多朋友說那邊人很多,排隊很久。聽的我們都是心慌慌的,但玩好以...
    迷酒閱讀 565評論 1 2
  • 時間的風 為你我披沙揀金 張手撫下 癲醉的黃葉 不知這是什么世界 莊嚴的他不敢抬頭 開口大笑 窺不及合不合時宜 只...
    我的貓叫老板娘閱讀 641評論 7 8