Daniel Stott
Daniel Stott

Reputation: 39

Creating a new collection inside existing collection

I am currently trying to put a backbone model inside an already existing model. I was wondering if this is even possible.

var rf = this.collection.create(attrs, options);
Model.set(table, rf);

Thanks

Upvotes: 0

Views: 125

Answers (1)

Artem Baranovskii
Artem Baranovskii

Reputation: 1003

What you trying to do is "Nested Models & Collections". Backbone already has preferable approach. The common idea consist in storing of nested model directly in the instance of another model instead attributes.

So, you could create child model first and then pass it to parent model through options like the following:

var rf = this.collection.create(attrs, options);

var Model = Backbone.Model.extend({

  initialize: function(attributes, options) {
    _.isObject(options) || (options = {});

    if (options.child) {
        this.child = new options.child;
    }        
  }
});

var model = new Model({}, {child: rf});

If you want to get a fully supported tree-like Backbone models you could try to use one of the following plugins.

Hope this helps!

Upvotes: 1

Related Questions