/*
怎么处理地址改变
回退、前进怎么处理
a 标签处理
*/
class myRouter {
constructor () {
this.routers = {}
this.listerLink()
this.listerPopState()
}
listerLink () {
window.addEventListener('click', (e) =>{
let dom = e.target
if (dom.tagName === 'A' && dom.getAttribute('href')) {
e.preventDefault()
this.renderView(path)
}
}, false)
}
listerPopState (e) {
window.addEventListener('popstate', (e)=> {
const state = e.state || {},
path = state.path || ''
this.renderView(path)
}, false)
}
load () {
let path = location.pathname
this.renderView(path)
}
register (path, callback = function(){}) {
this.router[path] = callback
}
registerIndex () {
this.routers['/'] = callback
}
registerNotFound (callback = function(){}) {
this.routers['404'] = callback
}
registerError () {
this.routers['error'] = callback
}
push (path) {
history.pushState({ path }, null, path)
this.renderView(path)
}
renderView (path) {
let handle;
try {
if (!this.routers.hasOwnProperty(path)) {
handle = this.routers['404'] || function(){}
} else {
handle = this.routers[path]
}
handle(this)
} catch (e) {
console.log(e)
(this.routers['error'] || function(){}).call(this, e)
}
}
}
console