美文网首页
简单的前端路由实现

简单的前端路由实现

作者: DCbryant | 来源:发表于2017-10-11 13:22 被阅读9次
function Router() {
    this.routes = {};
    //{path:fn(){}}
    this.currentUrl = '';
}
//存储路由更新时的回调到回调数组routes中,回调函数将负责对页面的更新
Router.prototype.route = function(path, callback) {
    this.routes[path] = callback || function(){};
}
//执行当前url对应的回调函数,更新页面
Router.prototype.refresh = function() {
    this.currentUrl = location.hash.slice(1) || '/';
    this.routes[this.currentUrl]();
};
//监听浏览器 url hash 更新事件
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() {
    doSomeThing()
});
Router.route('/about', function() {
    doSomeThing()
});

相关文章

网友评论

      本文标题:简单的前端路由实现

      本文链接:https://www.haomeiwen.com/subject/gdcwyxtx.html