]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/router.js
7b2e9954622d40255298a839c177354ea1fb2578
[rails.git] / app / assets / javascripts / router.js
1 OSM.Router = function(rts) {
2   var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#\s]/g;
3   var optionalParam = /\((.*?)\)/g;
4   var namedParam    = /(\(\?)?:\w+/g;
5   var splatParam    = /\*\w+/g;
6
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 : '([^\/]+)';
13         })
14         .replace(splatParam, '(.*?)') + '(?:$|[?#])');
15
16     var route = {};
17
18     route.match = function(path) {
19       return regexp.test(path);
20     };
21
22     route.run = function(action, path) {
23       var params = [];
24
25       if (path) {
26         params = regexp.exec(path).map(function(param, i) {
27           return (i > 0 && param) ? decodeURIComponent(param) : param;
28         });
29       }
30
31       (controller[action] || $.noop).apply(controller, params);
32     };
33
34     return route;
35   }
36
37   var routes = [];
38   for (var r in rts)
39     routes.push(Route(r, rts[r]));
40
41   routes.recognize = function(path) {
42     for (var i = 0; i < this.length; i++) {
43       if (this[i].match(path)) return this[i];
44     }
45   };
46
47   var currentPath = window.location.pathname,
48     currentRoute = routes.recognize(currentPath);
49
50   currentRoute.run('load', currentPath);
51
52   if (window.history && window.history.pushState) {
53     $(window).on('popstate', function() {
54       var path = window.location.pathname;
55       if (path === currentPath) return;
56       currentRoute.run('unload');
57       currentPath = path;
58       currentRoute = routes.recognize(currentPath);
59       currentRoute.run('popstate', currentPath);
60     });
61
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');
68       currentPath = path;
69       currentRoute = route;
70       currentRoute.run('pushstate', currentPath);
71       return true;
72     }
73   } else {
74     return function (url) {
75       window.location.assign(url);
76     }
77   }
78 };