封装为函数的版本:监听 & 刷新
function refresh() {
var req = location.hash.slice(1) || '/';
console.log(req);
}
function bind_uri_refresh() {
window.addEventListener('load', refresh.bind(this), false);
window.addEventListener('hashchange', refresh.bind(this), false);
}
bind_uri_refresh();
封装为类的版本:封装监听事件
function Router() {
}
Router.prototype.refresh = function() {
console.log(location.hash.slice(1));
this.currentUrl = location.hash.slice(1) || '/';
};
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();
增加回调功能的版本:将URI映射为对应的函数
完整代码来源于原生JS实现一个简单的前端路由(路由实现的原理)
function Router() {
this.routes = {};
this.currentUrl = '';
}
Router.prototype.route = function(path, callback) {
this.routes[path] = callback || function(){};
};
Router.prototype.refresh = function() {
console.log(location.hash.slice(1));
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.route('/', function() {
console.log("test");
});
Router.route('/1', function() {
console.log("aaa");
});
Router.route('/2', function() {
console.log("bbb");
});
|