Hash路由简单实现

54 阅读1分钟
(function(global) {

        function Router(){
            this.before = null; //切换前
            this.after = null; // 切换后
            this.routes=[];
            this.redirectRoute="";
            this.routeId="";
        };

        Router.prototype = {

            //获取路由的路径和详细参数
            getParamsUrl: function() {
                var hashDeatail = location.hash.split("?"),
                    hashName = hashDeatail[0].split("#")[1],//路由地址
                    params = hashDeatail[1] ? hashDeatail[1].split("&") : [],//参数内容
                    query = {};
                for(var i = 0;i<params.length ; i++){
                    var item = params[i].split("=");
                    query[item[0]] = item[1]
                }
                return     {
                    path:hashName,
                    query:query
                }
            },
            init:function (config) {
                var that = this;
                that.routes = config.routes;
                that.routeId = config.routeId;
                this.redirectRoute = config.redirect;
                that.urlChange();
                //路由切换
                global.addEventListener('hashchange',function(){
                    that.urlChange();
                });
            },
            freshUrl:function(){
                this.urlChange();
            },
            //路由处理
            urlChange:function(){
                var that = this;
                var currentHash = that.getParamsUrl();
                if(!$.isEmptyObject(currentHash.query)){
                    for(var i = 0 ; i< this.routes.length;i++){
                        var path = this.routes[i].path;
                        var num = path.indexOf(':');
                        var route = path.slice(0,num+1);
                        var pid = "";
                        if (num>0){
                            pid = path.slice(num+1);
                            that.loadHtml(this.routes[i].templateUrl,function (htmlData) {
                                $(that.routeId).html(htmlData);
                            })
                            //location.href="#"+route+"?"+pid+"="+currentHash.query[pid];
                        };
                    }
                }else{
                    for(var i = 0 ; i< this.routes.length;i++){
                        if(that.routes[i].path===currentHash.path){
                            that.loadHtml(this.routes[i].templateUrl,function (htmlData) {
                                $(that.routeId).html(htmlData);
                            });
                            console.log("加载");

                        }else{
                            //不存在的地址重定向到首页
                            console.log("没加载");
                        };
                    }
                }



            },

            map: function() {
                var that = this;
                for (var i = 0; i < that.routes.length; i++) {
                    var route = that.routes[i];

                    var newPath = route.path;
                    var path = newPath.replace(/\s*/g, ""); //过滤空格
                    that.routes[path] = {
                        callback: route.callback, //回调
                    }
                }
            },
            loadHtml:function (url,cal) {
                $.ajax({
                    type: 'GET',
                    url: url,
                    dataType: 'html',
                    success: function (data) {
                       cal(data)
                    }
                });
            }



        }

        global.linkTo =function(url,param){
            var pathUrl = url;
            if(param){
                pathUrl+="/?";
                for (var key in param){
                    //只遍历对象自身的属性,而不包含继承于原型链上的属性。
                    if (param.hasOwnProperty(key) === true){
                        pathUrl+=key+'='+param[key]+'&';
                    }
                }
                pathUrl=pathUrl.slice(0,-1);
            }
            location.href="#"+pathUrl;
        };
        $.ajaxPrefilter(function( options, original_Options, jqXHR ) {
            options.async = true;
        });
        // 注册到 window 全局
        global.Router = Router;
        global.router = new Router();

    })(window);