最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - backbone.js parse 1 element (the Id) - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question asked Jul 6, 2011 at 17:35 Shawn McleanShawn Mclean 57.5k96 gold badges281 silver badges412 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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.

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.

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;
发布评论

评论列表(0)

  1. 暂无评论