Chen-Tai
Chen-Tai

Reputation: 3473

Backbone model urlRoot share the middle part of api

I want to fetch an api and the format is like apps/[:id]/result.

For most of the example or documentation about setting the urlRoot is based on having the same root url.

But my problem is the api share the same root and the end of the api name.

I try to use below code, but it doesn't work.

var Model = Backbone.Model.extend({
    urlRoot: "/apps"
})

var model = new Model({id: 123123 + "/content"]}) //123123 just fake id 

Does it any way to change only the middle of the id?

Or in this situation, use urlRoot is inappropriate?

Upvotes: 0

Views: 119

Answers (1)

joews
joews

Reputation: 30330

Backbone's persistence methods, which are built around url and urlRoot, are designed for RESTful persistence. Each method is designed to communicate with a server using well-defined semantics (GET /path means list, PUT /path/:id means update, etc).

Chaning the meaning of id is a bad idea because you depart break those semantics, meaning that a) your model will not work with create, update or delete REST operations, and b) your code will become difficult to understand since id will no longer be a descriptive variable name. Backbone uses id frequently in Models and Collections, so it would be a very bad idea to change its meaning.

If you are not using a REST API, or you have a particular operation that does not fit that paradigm (like searching), it is best to implement your own methods to make custom HTTP requests.

In your case, something like this should work as you expect:

var Model = Backbone.Model.extend({
  urlRoot: "/apps",
  fetchResult: function() {
    return $.ajax({
      url: this.url() + '/result'
    }).then(function(response) {
       // do something with response
       // return response, or the result of your processing,
       //  for downstream promise handlers
       return response;
    }, function() {
      console.error('fetchResult failed');
    })
  },

})

With this approach the RESTful URLs work as designed and you don't lose the semantics of id.

Upvotes: 1

Related Questions