Skip to content

Instantly share code, notes, and snippets.

@juuliaans
Last active December 19, 2015 23:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juuliaans/6034831 to your computer and use it in GitHub Desktop.
Save juuliaans/6034831 to your computer and use it in GitHub Desktop.
URL builder for Backbone-like router.
resolveURL: function (route, params, appendRoot) {
var appendRoot = (appendRoot == false) ? false : true;
var route, params;
var href = "";
var regExpAllNormalParams = /(\(\?)?\/:\w+/g;
var regExpAllOptionalParams = /\((.*?)\)/g;
href = router.routes[route];
for (var p in params) {
//matchs normal parameters
var regExpNormal = new RegExp("(\\(\\?)?:"+ p);
//matchs optional parameters
var regExpOptional = new RegExp("\\((/:" + p + ")\\)");
//matchs named parameters
var regExpNamedParams = new RegExp("\\((/([^\\/]+):"+p+")\\)");
//this is if the parameter has any special way of encoding itself (such as a date could be enconded as text yy-mm-dd)
//var value = router.encodeParameter(p, params[p]);
var nameOptParam = href.match(regExpNamedParams);
if (nameOptParam != null) {
href = href.replace(regExpNamedParams, "/" + ((nameOptParam[2]) ? nameOptParam[2] : "") + escape(value));
}
href = href.replace(regExpOptional, "/" + escape(value));
href = href.replace(regExpNormal, escape(value));
}
href = href.replace(regExpAllOptionalParams, "");
href = href.replace(regExpAllNormalParams, "");
//if the app has any root url
//href = (appendRoot) ? app.root + href : href;
return href;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment