Created
April 12, 2016 02:46
-
-
Save Ke-/c905f1e518169ca2cc33e3f766bbe012 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var router = (function() { | |
var self = {} | |
var usehistory = window && window.history.pushState ? 1 : 0; | |
self.routes = {} | |
self.go = function(url,title,state){ | |
self.push(url,title,state) | |
self.execute(url) | |
} | |
self.push = function(url,title,state){ | |
if(usehistory && url != location.pathname){ | |
if(title && document) document.title = title | |
history.pushState(state || {}, title || '', url) | |
} | |
} | |
self.route = function(url, controller) { | |
var match = self.trim(url) | |
self.routes[match] = { | |
url: url, | |
controller: controller | |
}; | |
} | |
self.process = function(){ | |
var url = location.hash.slice(1) || location.pathname || '/' | |
self.execute(url) | |
} | |
self.execute = function(url){ | |
var route = self.routes[self.trim(url)] | |
if(url[0] == '/') url = url.slice(1) | |
if(route && route.controller) { | |
// (collection, id, action) | |
route.controller.apply(null, url.split('/')) | |
} | |
} | |
self.trim = function(url){ | |
if(url[0] == '/') url = url.slice(1) | |
return url.split('/')[0] | |
} | |
// Listen on history change: | |
window.addEventListener('popstate', self.process); | |
// Listen on hash change: | |
window.addEventListener('hashchange', self.process); | |
// Listen on page load: | |
window.addEventListener('load', self.process); | |
return self | |
})() | |
function routes(map) { | |
for(var i in map){ | |
router.route((i[0] != '/' ? '/' : '') + i,map[i]) | |
} | |
} | |
function route(url, controller) { | |
router.route(url, controller) | |
} | |
// support CommonJS | |
if (typeof exports === 'object') | |
module.exports = router | |
// support AMD | |
else if (typeof define === 'function' && define.amd) | |
define(function() { return router }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment