Skip to content

Instantly share code, notes, and snippets.

@aurri
Last active August 29, 2015 14:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aurri/faf17a9f5c1f7d3ede2d to your computer and use it in GitHub Desktop.
Save aurri/faf17a9f5c1f7d3ede2d to your computer and use it in GitHub Desktop.
Minimal routing library
/////////////////////////////////////////////////
//// 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