標籤:對象 location turn 頁面 函數 pat back 改變 hang
說一下前端路由實現的簡要原理,以 hash 形式(也可以使用 History API 來處理)為例,
當 url 的 hash 發生變化時,觸發 hashchange 註冊的回調,回調中去進行不同的操作,進行不同的內容的展示。
直接看代碼或許更直觀。
1 function Router() { 2 this.routes = {}; 3 this.currentUrl = ‘‘; 4 } 5 Router.prototype.route = function(path, callback) { 6 this.routes[path] = callback || function(){}; 7 }; 8 Router.prototype.refresh = function() { 9 this.currentUrl = location.hash.slice(1) || ‘/‘;10 this.routes[this.currentUrl]();11 };12 Router.prototype.init = function() {13 window.addEventListener(‘load‘, this.refresh.bind(this), false);14 window.addEventListener(‘hashchange‘, this.refresh.bind(this), false);15 }16 window.Router = new Router();17 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 anythingfunction changeBgColor(color) { content.style.backgroundColor = color;}Router.route(‘/‘, function() { changeBgColor(‘white‘);});Router.route(‘/blue‘, function() { changeBgColor(‘blue‘);});Router.route(‘/green‘, function() { changeBgColor(‘green‘);});
原生JS實現一個簡單的前端路由(原理)