Skip to content

Instantly share code, notes, and snippets.

@arendjr
Created November 23, 2013 15:05
Show Gist options
  • Save arendjr/7615549 to your computer and use it in GitHub Desktop.
Save arendjr/7615549 to your computer and use it in GitHub Desktop.
Backbone.js-based Router implementation
function Router() {
var self = this;
setTimeout(function() {
window.addEventListener("popstate", _.bind(self._onStatePopped, self));
self._activateRoute();
}, 0);
}
_.extend(Router.prototype, {
navigate: function(path) {
history.pushState({}, "", path);
},
routes: {
"": function(path) { /* show main page */ },
"dashboard(/:path)": function(path) { /* show dashboard */ }
},
_activateRoute: function() {
function routeToRegExp(route) {
var optionalParam = /\((.*?)\)/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
route = route
.replace(escapeRegExp, "\\$&")
.replace(optionalParam, "(?:$1)?")
.replace(namedParam, function(match, optional) {
return optional ? match : '([^\/]+)';
})
.replace(splatParam, "(.*?)");
return new RegExp("^" + route + "$");
}
var path = location.pathname.slice(1);
var params;
var route = _.find(this.routes, function(handler, route) {
var regex = routeToRegExp(route);
if (regex.test(path)) {
params = _.map(regex.exec(path).slice(1), function(param) {
return param ? decodeURIComponent(param) : null;
});
return true;
} else {
return false;
}
});
if (route) {
route.apply(this, params);
}
},
_onStatePopped: function() {
this._activateRoute();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment