zoukankan      html  css  js  c++  java
  • 一个极简前端路由实现

    说一下前端路由实现的简要原理,以 hash 形式(也可以使用 History API 来处理)为例,当 url 的 hash 发生变化时,触发 hashchange 注册的回调,回调中去进行不同的操作,进行不同的内容的展示。直接看代码或许更直观。

    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 对象实现,主要提供三个方法

    • init 监听浏览器 url hash 更新事件
    • route 存储路由更新时的回调到回调数组routes中,回调函数将负责对页面的更新
    • refresh 执行当前url对应的回调函数,更新页面

    Router 调用方式以及呈现效果如下:点击触发 url 的 hash 改变,并对应地更新内容(这里为 body 背景色)

    <ul> 
        <li><a href="#/">turn white</a></li> 
        <li><a href="#/blue">turn blue</a></li> 
        <li><a href="#/green">turn green</a></li> 
    </ul> 
    var content = document.querySelector('body');
    // change Page anything
    function changeBgColor(color) {
        content.style.backgroundColor = color;
    }
    Router.route('/', function() {
        changeBgColor('white');
    });
    Router.route('/blue', function() {
        changeBgColor('blue');
    });
    Router.route('/green', function() {
        changeBgColor('green');
    });

  • 相关阅读:
    安亦行
    [SCOI2010]连续攻击游戏 二分图匹配
    [USACO11JAN]Roads and Planes G
    CF796C Bank Hacking
    括号类问题总结 持续更新
    CF1216E Numerical Sequence Hard Version 数学
    POJ3613 Cow Relays 矩阵快速幂
    倍增法求lca(最近公共祖先)
    Codeforces C. Jzzhu and Cities(dijkstra最短路)
    Codeforces B. Mouse Hunt(强连通分解缩点)
  • 原文地址:https://www.cnblogs.com/webenh/p/7159096.html
Copyright © 2011-2022 走看看