Skip to content

Instantly share code, notes, and snippets.

@hetsch
Created March 14, 2012 09:20
Show Gist options
  • Save hetsch/2035325 to your computer and use it in GitHub Desktop.
Save hetsch/2035325 to your computer and use it in GitHub Desktop.
Backbone named parameter routing
Components.Router = Backbone.Router.extend({
// @todo also support unnamed params
// 'page/edit/(?<language>[a-z]{2})/(?<entityId>[a-z0-9]{24})/(.*)'
route: function(route, name, callback) {
Backbone.history || (Backbone.history = new Backbone.History);
if (!XRegExp.isRegExp(route)) route = this._routeToRegExp(route);
if (!callback) callback = this[name];
Backbone.history.route(route, _.bind(function(fragment) {
var routeParams = XRegExp.exec(fragment, route),
namedRouteParams = [],
value,
namedArgs;
if (routeParams && callback) {
_.each(this._getFunctionArgumentNames(callback), function(name, idx) {
if(value = routeParams[name]) {
// apply at the function argument position
namedRouteParams[idx] = value;
}
});
// only call with namedParams
callback.apply(this, namedRouteParams);
}
this.trigger.apply(this, ['route:' + name].concat(routeParams));
Backbone.history.trigger('route', this, name, routeParams);
}, this));
return this;
},
_routeToRegExp: function(route) {
return new XRegExp('^' + route + '$');
},
_getFunctionArgumentNames: function(func) {
return func.toString().match(/function\s+\w*\s*\((.*?)\)/)[1].split(/\s*,\s*/);
}
});
@hetsch
Copy link
Author

hetsch commented Mar 14, 2012

This snippet needs XRegExp lib. http://xregexp.com/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment