Refer model from collection

39 views Asked by At

I am using Backbone to structure my web application, this is my situation:

Section = Backbone.Model.extend({
     initialize: function(){
          this.set("elements", new ElementCollection());
     }
})

ElementCollection = Backbone.Model.extend({

     model: ElementModel

})

The meaning of this relation is that Section contains multiple Elements. My goal now is to refer, from a ElementCollection to its parent Section model.

How can I achieve this?

I tried to set a property in the Collection, like:

this.set("parentSection", theParentSection")

but this does not do the trick, in fact the standard set method in a Collection adds a model inside it, which breaks all my structure.

1

There are 1 answers

0
vvahans On

You can pass parent model to the collection when initializing it:

Section = Backbone.Model.extend({
     initialize: function(){
          this.set("elements", new ElementCollection([], {parentModel: this}));
     }
})

ElementCollection = Backbone.Collection.extend({
     initialize: function (options) {
         this.parentSection = options.parentModel;
     }, 
     model: ElementModel
})