Better solution for nested Backbone.js collections

前端 未结 4 582
一个人的身影
一个人的身影 2021-01-30 12:04

Many of my Backbone models often deal with nested models and collections, so far I\'m using a combination of defaults, parse and toJSON ma

4条回答
  •  無奈伤痛
    2021-01-30 12:22

    I'v found out that with this approach Supplier's toJSON function will get outdated, so it might be a good idea to do reassemble back it's JSON state from it's, and it's children's data.

    ACME.Supplier = Backbone.Model.extend({
        initialize: function(options) {
            this.tags = new ACME.Tags(options.tags);
        },
    
        parse: function(res) {
            res.tags && this.tags.reset(res.tags);
    
            return res;
        },
    
        toJSON: function({
            return _.extend(
                _.pick(this.attributes, 'id', 'attr1', 'attr2'), {
                tags: this.tags.toJSON(),
            });
        })
    

    });

提交回复
热议问题