Last active
August 29, 2015 14:03
-
-
Save aurri/faf17a9f5c1f7d3ede2d to your computer and use it in GitHub Desktop.
Minimal routing library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///////////////////////////////////////////////// | |
//// Minimal routing library (IE10+) | |
///////////////////////////////////////////////// | |
// Listen to url changes: | |
// route(function(param, param...){}) - will get /param/param, split as arguments | |
// Navigate to path: | |
// route.to(path) - redirect to new path | |
// route.to(path, true) - redirect to new path, replacing current url | |
// Change current path (won't trigger the handlers): | |
// route.set(path) - set new path | |
// route.set(path, true) - set new path, replacing current url | |
var route = module.exports = listen | |
// Hash(less) urls | |
route.hash = true | |
function type(){ return route.hash ? 'hash' : 'pathname' } | |
// Listen | |
function listen(cb){ | |
window.addEventListener('popstate', changed) | |
window.addEventListener('DOMContentLoaded', changed) | |
function changed(){ | |
var self = {url:url(), path:path(), args:args()} | |
cb.apply(self, self.args) | |
} | |
} | |
function url(){ return location[type()] } | |
function path(){ return url().substr(1) } | |
function args(){ return path().split('/').slice(1) } | |
// Update | |
route.to = function(path, replace){ update[1-!replace](toUrl(path)) } | |
route.set = function(path, replace){ update[3-!replace](toUrl(path)) } | |
function toUrl(path){ return route.hash ? '#'+path.split('#').pop() : path } | |
var update = [ | |
function(path){ location[type()] = path }, | |
function(path){ location.replace(path) }, | |
function(path){ history.pushState(0, 0, path) }, | |
function(path){ history.replaceState(0, 0, path) } | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment