The My Backbone application interacts with an API that exists on another server. Backbone.sync will generate relative URLs by default. The easiest way to add an absolute server path would be something like this:
MyApp.BASE_URL = "https://api.someOtherSite.com" class MyApp.Model extends Backbone.Model urlRoot: "#{MyApp.BASE_URL}/my_app_url"
However, I would prefer not to do this because it is NOT DRY. I thought I could try something like the following by overriding Backbone.sync :
do (Backbone) -> BASE_URL = 'https://api.someOtherSite.com' baseSync = Backbone.sync Backbone.sync = (method, model, options) -> url = _.result(model, 'url') options.url = "#{BASE_URL}/#{url}" if url && !options.url baseSync method, model, options
However, this is a problem for other parts of the code, as the options object is passed around. * (explanation for interested below)
Is there a recommended clean and harsh way to add a server path to the beginning of all URLs created with Backbone.sync ?
* If the synchronized model is an instance of Backbone.Collection , this options object will be passed to the collection model constructor. A URL is one of the few properties that will be directly bound to the model if it is passed as part of the options object. This breaks sync into any models created in the collection, because now they have a set of URLs attached to them instead of the url method, which generates the corresponding URL using urlRoot or the url collection.
Aaron source share