Created
March 14, 2012 09:20
-
-
Save hetsch/2035325 to your computer and use it in GitHub Desktop.
Backbone named parameter routing
This file contains 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
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*/); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This snippet needs XRegExp lib. http://xregexp.com/