UNPKG

backbone-named-routes

Version:

Backbone router implementation with named routes (aliases) for easy client side links generation

1 lines 1.82 kB
!function(a,b){"function"==typeof define&&define.amd?define(["jquery","backbone","underscore"],b):"object"==typeof module&&module.exports?module.exports=b(require("jquery"),require("backbone"),require("underscore")):a.BackboneNamedRouter=b(a.jQuery,a.Backbone,a._)}(this,function(a,b,c){var d=function(a){return a?a.replace(/\/$/,""):""},e=function(a,b){return a.substr(0,b.length)===b};return b.Router.extend({constructor:function(a){this.options=c.extend({baseUrl:"undefined"!=typeof window?window.location.protocol+"//"+window.location.host:"",usesPushState:!1,root:""},a),b.Router.apply(this,arguments)},getHistoryStartParams:function(a){return c.extend({pushState:this.options.usesPushState,root:this.options.root},a)},route:function(a,c,d){this.namedRoutes=this.namedRoutes||{},this.namedRoutes[c]=a,b.Router.prototype.route.apply(this,arguments)},url:function(b,c,e){var f=this.namedRoutes[b],g=this.options.baseUrl,h=this.options.usesPushState,i=this.options.root,j="";if(void 0===f)throw new Error('Route "'+b+'" is not defined');return 0===f.length?j=g+d(i):(f=f.replace(/\((.*?)\)|(\(\?)?:\w+|\*\w+/g,function(a){var d=a.match(/\:\w+|\*\w+/)[0].slice(1),e=c[d],f=void 0!==e;if(a.match(/\((.*?)\)/g))return f?a.replace(/\(|\)/g,"").replace(/\:\w+/,e):"";if(f)return e;throw new Error('Required route parameter "'+d+'" for route "'+b+'" is missing')}),j=h?g+i+f:g+d(i)+"#"+f),e&&(j+="?"+a.param(e)),j},navigateToUrl:function(c,f){var g=c instanceof a?c.attr("href"):c,h=this.options.baseUrl,i=this.options.usesPushState,j=d(this.options.root);e(g,h)&&(g=g.replace(h,"")),e(g,j)&&(g=g.replace(j,"")),e(g,"/")&&(g=g.slice(1)),!i&&e(g,"#")&&(g=g.slice(1)),f&&g===b.history.fragment?b.history.loadUrl(g):this.navigate(g,{trigger:Boolean(f)})},navigateToRoute:function(a,b,c,d){this.navigateToUrl(this.url(a,b,c),d)}})});