hash模式实现前端路由

来源:互联网 发布:锐捷mac怎么设置 编辑:程序博客网 时间:2024/03/28 17:46
    function Router() {        this.routes = {};        this.currentUrl = '';    }    Router.prototype.route = function(path, callback) {        this.routes[path] = callback || function(){};    };    Router.prototype.refresh = function() {        this.currentUrl = location.hash.slice(1) || '/';        this.routes[this.currentUrl]();    };    Router.prototype.init = function() {        window.addEventListener('load', this.refresh.bind(this), false);        window.addEventListener('hashchange', this.refresh.bind(this), false);    }    window.Router = new Router();    window.Router.init();    Router.route('/', function() {        console.log('home');    });    Router.route('/about', function() {        console.log('about');    });    Router.route('/about/test', function() {        console.log('about_test');    });
原创粉丝点击