Home > Article > Web Front-end > js implements custom routing
This article implements custom routing, mainly the use of event hashchange, and then encapsulates it according to our business needs.
First implement a router class and instantiate it.
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(); }
The only thing that needs to be noted above is that when using addEventListener, you need to pay attention to the use of the bind function, because I stepped on a trap and realized $.proxy().
You can use two methods to register when using it above, but the second one depends on the first one.
Method one:
var Router = router({ '/' : function(){content.style.backgroundColor = 'white';}, '/1': function(){content.style.backgroundColor = 'blue';}, '/2': function(){content.style.backgroundColor = 'green';} })
Method two:
Router.route('/3',function(){ content.style.backgroundColor = 'yellow'; })
Complete code:
<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>
The above is the entire content of this article. I hope that the content of this article can bring some help to everyone's study or work. I also hope to support the PHP Chinese website!
For more articles related to js implementation of custom routing, please pay attention to the PHP Chinese website!