Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a global REST root url in a Backbone.js application

Tags:

backbone.js

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.

like image 685
Shawn Mclean Avatar asked Apr 28 '12 16:04

Shawn Mclean


2 Answers

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)

<!DOCTYPE html>
<head>
  <meta charset="utf-8">

  <script>
    var require = {
      config: {
        // key name is module, value is data to give module
        'models/Base': {
          apiUrl: '/some/path/to/api',
        }
      }
    }
  </script>
<script data-main="js/main" src="vendor/require/require-jquery.js"></script>
</head>
<body></body>
</html>

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)

define(['module', 'backbone'],
  function(module, Backbone){

    return Backbone.Model.extend({
      getApiUrl: function(){
        return module.config().apiUrl;
      }
    });

  }
);

Finally, extend all of your Backbone models from that base, like this:

js/models/User.js

define(['models/Base'],
  function(BaseModel){

    return BaseModel.extend({
      urlRoot: function(){
        return this.getApiUrl() + '/user';
      }
      // ... more cool stuff here
    });

  }
);

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

like image 87
Bart Avatar answered Oct 21 '22 05:10

Bart


What I understand is :

You have several models: model1 and model2

The root URL can be either http://api.site.com or http://localhost:8080 depending on whether you are working locally or externally. And someday it could be http://api.anothersite.com

I would do somthing like this then :

// Global var before any other JS code, you comment line depending on which one applies
var ROOT = 'http://api.site.com'
// var ROOT = 'http://localhost:8080'

var Model1 = Backbone.Model.extend({
urlRoot: ROOT+'/model1',
...
});

var Model2 = Backbone.Model.extend({
urlRoot: ROOT+'/model2',
...
});

But be careful with this, you may forget to switch from one url to the other one when commiting. Better is to handle relative paths if they'd apply.

like image 31
Augustin Riedinger Avatar answered Oct 21 '22 05:10

Augustin Riedinger