1 OSM.Router = function(rts) {
2 var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
3 var optionalParam = /\((.*?)\)/g;
4 var namedParam = /(\(\?)?:\w+/g;
5 var splatParam = /\*\w+/g;
7 function Route(path, controller) {
8 var regexp = new RegExp('^' +
9 path.replace(escapeRegExp, '\\$&')
10 .replace(optionalParam, '(?:$1)?')
11 .replace(namedParam, function(match, optional){
12 return optional ? match : '([^\/]+)';
14 .replace(splatParam, '(.*?)') + '(?:\\?.*)?$');
18 route.match = function(path) {
19 return regexp.test(path);
22 route.run = function(action, path) {
26 params = regexp.exec(path).map(function(param, i) {
27 return (i > 0 && param) ? decodeURIComponent(param) : param;
31 (controller[action] || $.noop).apply(controller, params);
39 routes.push(Route(r, rts[r]));
41 routes.recognize = function(path) {
42 for (var i = 0; i < this.length; i++) {
43 if (this[i].match(path)) return this[i];
47 var currentPath = window.location.pathname + window.location.search,
48 currentRoute = routes.recognize(currentPath);
50 currentRoute.run('load', currentPath);
52 if (window.history && window.history.pushState) {
53 $(window).on('popstate', function() {
54 var path = window.location.pathname + window.location.search;
55 if (path === currentPath) return;
56 currentRoute.run('unload');
58 currentRoute = routes.recognize(currentPath);
59 currentRoute.run('popstate', currentPath);
62 return function (url) {
63 var path = url.replace(/#.*/, ''),
64 route = routes.recognize(path);
65 if (!route) return false;
66 window.history.pushState({}, document.title, url);
67 currentRoute.run('unload');
70 currentRoute.run('pushstate', currentPath);
74 return function (url) {
75 window.location.assign(url);