0

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.

steo
  • 4,586
  • 2
  • 33
  • 64
  • 1
    Something like this http://stackoverflow.com/a/11417645/1071630 ? – nikoshr Nov 17 '14 at 09:42
  • That could be a solution. What I want to do is to refer model from collection and not from every model inside it – steo Nov 17 '14 at 09:49

1 Answers1

1

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
})
vvahans
  • 1,849
  • 21
  • 29