In backbone.js, you have to set the rooturl of every model manually. Is there a way we can set this in a single location once and all models will use it?
For eg. api.site.com
will be the REST service, but for testing purpose, it may be at localhost:1000
I need to be able to change the root url of the service easily and not have them all over the place in the many models that exist in the application.
Adapted from https://coderwall.com/p/8ldaqw/add-a-root-url-to-all-backbone-api-request
I've been playing around with the most elegant way to do this when using Backbone with AMD (require.js). This is what I've come up with, and like best [so far].
First, bootstrap the data in, as described here.
index.htm (application entry point)
Next, define a base class for Backbone models, like this:
js/models/Base.js (notice this module name matches the module name in config above)
Finally, extend all of your Backbone models from that base, like this:
js/models/User.js
This is tangentially related to an earlier question I had regarding Backbone and Require.JS.
Related reading: http://requirejs.org/docs/api.html#config-moduleconfig
This is really old post, but I think that my version can be useful for someone. I use backbone with require.js and my server-side and client-side completely separated. I give to know for the client app where is API root at the same time, when I declare requirejs script:
and then i get in my backbone module:
This is the most elegant way which I could find..
Just start your url from '/'. Thus you'll be not depend on either localhost or real domain.
Not sure what exactly you mean setting
urlRoot
for every model manually. Presumably you doright? Then each model instance naturally has the same
urlRoot
.Any other model instance of sayMyOtherModel
would have some differenturlRoot
.If for some reason you need to be using the same
urlRoot
, I would guess it would be because the models share attributes. This should hint to inheritance or extension so you could do:In my opinion the best way to achieve this is by overriding the
Backbone.sync
method, and prepend your root url there. This because it's not the responsibility of the model to know the API domain.And then you can create your models as you would normally do:
I use this same method to append an
.json
extension to all URL's to prevent JSON flashes through browser cache.