js實現(xiàn)自定義路由
本文實現(xiàn)自定義路由,主要是事件hashchange的使用,然后根據(jù)我們的業(yè)務(wù)需求封裝。
首先實現(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()。
上邊使用的時候可以使用兩種方法進(jìn)行注冊,但第二種是依賴第一種的。
方法一:
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)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
bootstrap-Treeview實現(xiàn)級聯(lián)勾選
這篇文章主要為大家詳細(xì)介紹了bootstrap-Treeview實現(xiàn)級聯(lián)勾選,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11
如何使用require.context實現(xiàn)優(yōu)雅的預(yù)加載
這篇文章主要介紹了使用require.context實現(xiàn)優(yōu)雅的預(yù)加載?,需要的朋友可以參考下2023-05-05
利用javascript實現(xiàn)web頁面中指定區(qū)域打印
將需要打印的課程表的table放入div標(biāo)簽中,然后指定出需要打印的區(qū)域,最后調(diào)用window.print打印指定內(nèi)容2013-10-10
JavaScript兼容性總結(jié)之獲取非行間樣式案例
這篇文章主要介紹了JavaScript兼容性總結(jié)之獲取非行間樣式的相關(guān)資料,需要的朋友可以參考下2016-08-08

