js實現(xiàn)自定義路由
本文實現(xiàn)自定義路由,主要是事件hashchange的使用,然后根據(jù)我們的業(yè)務需求封裝。
首先實現(xiàn)一個router的類,并實例化。
function _router(config){ this.config = config ? config : {}; } _router.prototype = { event:function(str,callback){ var events = str.split(' '); for (var i in events) window.addEventListener(events[i],callback,false); }, init: function() { this.event('load hashchange',this.refresh.bind(this)); return this; }, refresh: function() { this.currentUrl = location.hash.slice(1) || '/'; this.config[this.currentUrl](); }, route: function(path,callback){ this.config[path] = callback || function(){}; } } function router (config){ return new _router(config).init(); }
上邊唯一需要注意的是,在使用addEventListener的時候,需要注意bind函數(shù)的使用,因為我是踩了坑,這才體會到$.proxy()。
上邊使用的時候可以使用兩種方法進行注冊,但第二種是依賴第一種的。
方法一:
var Router = router({ '/' : function(){content.style.backgroundColor = 'white';}, '/1': function(){content.style.backgroundColor = 'blue';}, '/2': function(){content.style.backgroundColor = 'green';} })
方法二:
Router.route('/3',function(){ content.style.backgroundColor = 'yellow'; })
完整代碼:
<html> <head> <title></title> </head> <body> <ul> <li><a href="#/1">/1: blue</a></li> <li><a href="#/2">/2: green</a></li> <li><a href="#/3">/3: yellow</a></li> </ul> <script> var content = document.querySelector('body'); function _router(config){ this.config = config ? config : {}; } _router.prototype = { event:function(str,callback){ var events = str.split(' '); for (var i in events) window.addEventListener(events[i],callback,false); }, init: function() { this.event('load hashchange',this.refresh.bind(this)); return this; }, refresh: function() { this.currentUrl = location.hash.slice(1) || '/'; this.config[this.currentUrl](); }, route: function(path,callback){ this.config[path] = callback || function(){}; } } function router (config){ return new _router(config).init(); } var Router = router({ '/' : function(){content.style.backgroundColor = 'white';}, '/1': function(){content.style.backgroundColor = 'blue';}, '/2': function(){content.style.backgroundColor = 'green';} }) Router.route('/3',function(){ content.style.backgroundColor = 'yellow'; }) </script> </body> </html> <script> </script>
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
js 靜態(tài)動態(tài)成員 and 信息的封裝和隱藏
一下用面向?qū)ο蟮南嚓P(guān)概念來解釋js中的仿面向?qū)ο?,因為js中不像其他語言,不存在面向?qū)ο笳Z言的相關(guān)特性2011-05-05javascript中動態(tài)加載js文件多種解決辦法總結(jié)
這篇文章主要介紹了javascript中動態(tài)加載js文件多種解決辦法,有需要的朋友可以參考一下2013-11-11JavaScript獲取radio選中值的幾種常用方法小結(jié)
這篇文章主要介紹了JavaScript獲取radio選中值的幾種常用方法,結(jié)合實例形式總結(jié)分析了javascript獲取radio選中值的常見實現(xiàn)方法與操作注意事項,需要的朋友可以參考下2023-06-06