2

For a id on a model in backbone, its just id and all lower cased. What if my Id on the server is called UserId. In the parse method for backbone, how do I change UserId to id and use the same names for all other properties?

For eg.

window.User = Backbone.Model.extend({
    defaults:
       {
           UserId: 0, // <--can i just tell backbone that this is my id?
           Name: '',
           Age: 0
       }
    parse: function(response){
           var model = response;
           model.id = response.UserId;
           return model;
       }
});

Is there a better way to do this?

How about telling backbone model that my id is of type UserId.

Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

3 Answers3

7

You have to say Backbone what property is your id using the idAttribute in the model:

window.User = Backbone.Model.extend({
    idAttribute: "UserId",
    ...
})

and everything works fine :). Backbone will create a id property for you and collections of this model will get() by your UserId.

mauromartini
  • 338
  • 1
  • 5
2

Do it like so:

parse: function(response) {
  var attrs = {};
  attrs.id = response.UserId;
  return attrs;
}

Parse has the responsibility to return an attributes hash, not a model. As such, you need only transform the response into an attributes hash versus a model as you are doing.

Bill Eisenhauer
  • 6,183
  • 2
  • 30
  • 28
  • How would I do the same on a collection? Apparently when I use fetch(), it does not mitigate down to the Model.parse method – Shawn Mclean Jul 07 '11 at 03:11
  • The collection has a parse method too. Its responsibility is to return an array of hashes which represent the models to set in the collection. Take a look at the documentation on the method: http://documentcloud.github.com/backbone/#Collection-parse – Bill Eisenhauer Jul 07 '11 at 12:11
  • So once I'm using the parse method, I have to include this for all other properties? So for eg. `attrs.FirstName = response.FirstName;` etc. – Shawn Mclean Jul 08 '11 at 05:16
  • You do that or you grab a bunch of properties all at once. So perhaps use the extend function to copy properties into the attrs hash. – Bill Eisenhauer Jul 08 '11 at 12:14
0

To set the id i would do as mauromartini says. To change any other property you don't need to create any private variables, response from the server is just an object so manipulate it and return it.

window.User = Backbone.Model.extend({
  defaults: { UserId: 0 },
  parse: function(response){
    response.id = response.UserId;
    return response;
  }
});

you could also add the following before you return the object if you want to keep the model clean:

delete response.UserId;
andy t
  • 3,767
  • 3
  • 19
  • 14