Backbone.js model with collection

后端 未结 1 419
野趣味
野趣味 2020-12-23 20:10

I have 2 models and one collection. JobSummary is a model, JobSummaryList is a collection of JobSummary items, and then I have a

相关标签:
1条回答
  • 2020-12-23 20:50

    Your parse() function shouldn't set() anything, its a better practice to just return the attributes, Backbone will take care of setting it. e.g.

    parse: function(response) {
        response.summaryList = new JobSummaryList(response.summaryList);
        return response;
    }
    

    Whatever you return from parse() is passed to set().

    Not returning anything (which is like returning undefined) is the same as calling set(undefined), which could cause it not to pass validation, or some other unexpected results if your custom validate()/set() methods expects to get an object. If your validation or set() method fails because of that, the options.success callback passed to Backbone.Model#fetch() won't be called.

    Also, to make this more generic, so that set()ing to a plain object from other places (and not only from the server response) also effects it, you might want to override set() instead:

    set: function(attributes, options) {
        if (attributes.summaryList !== undefined && !(attributes.summaryList instanceof JobSummaryList)) {
            attributes.summaryList = new JobSummaryList(attributes.summaryList);
        }
        return Backbone.Model.prototype.set.call(this, attributes, options);
    }
    

    You might also find Backbone-relational interesting - it makes it much easier to deal with collections/models nested inside models.

    edit I forgot to return from the set() method, the code is now updated

    0 讨论(0)
提交回复
热议问题