简单的前端路由实现

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()
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容