Skip to content

Instantly share code, notes, and snippets.

@johnsoncheg
Created September 1, 2018 08:53
Show Gist options
  • Save johnsoncheg/9629955a6874b681961a50959f534838 to your computer and use it in GitHub Desktop.
Save johnsoncheg/9629955a6874b681961a50959f534838 to your computer and use it in GitHub Desktop.
simple-spa-router
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<ul>
<li><a data-href="/" href="#">home</a></li>
<li><a data-href="/about" href="#">about</a></li>
<li><a data-href="/topics" href="#">topics</a></li>
</ul>
<div id="content"></div>
</div>
<script src="./router.js"></script>
<script>
const router = new Router()
router.init()
router.route('/', _ => {
document.getElementById('content').innerHTML = 'Home';
})
router.route('/about', function() {
document.getElementById('content').innerHTML = 'About';
})
router.route('/topics', function() {
document.getElementById('content').innerHTML = 'Topics';
})
</script>
</body>
</html>
class Router {
constructor () {
this.currentUrl = ''
this.routes = {}
}
route (path, callback = function () {}) {
this.routes[path] = callback
}
updateView (url) {
if (this.routes[url]) this.routes[url]()
}
bindLink () {
const allLink = document.querySelectorAll('a[data-href]')
for (let i = 0, len = allLink.length; i < len; i++) {
allLink[i].addEventListener('click', e => {
e.preventDefault()
const url = e.target.getAttribute('data-href')
history.pushState({}, null, url)
this.updateView(url)
})
}
}
init () {
this.bindLink()
window.addEventListener('popstate', e => {
this.updateView(window.location.pathname)
})
window.addEventListener('load', e => {
this.updateView('/')
}, false)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment