Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js parse 1 element (the Id)

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.

like image 935
Shawn Mclean Avatar asked Apr 24 '26 03:04

Shawn Mclean


1 Answers

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.

like image 72
mauromartini Avatar answered Apr 26 '26 16:04

mauromartini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!