kLezer
kLezer

Reputation: 221

What is the best practice for nested models in Backbone?

I have a Collection "Map" and two models "Zone" and "Section".

Zone attributes:
    zone_title: "New zone"
    width: 0
    height: 0
    order: 0
    sections: []

Section attributes:
    section_title: "New section"
    content: "Some texts"
    order: 0

How do I associate these two models? each Zone can have many Section.

Each Zone can be sortable within the Map and each Section can be sortable within the Zone.

What is the best practice to do that?

Upvotes: 1

Views: 52

Answers (2)

user456176
user456176

Reputation: 56

I suggest you take a look at Backbone-relational--I think it covers your use case.

Since you asked about the best practice, from what I can gather, the best practice when using Backbone without any plugins is that models should always be shallow. You'd load a collection of Zones by fetching the Map collection, but those Zones would be shallow. For each Zone, you'd make a separate call to fetch the collection of Sections for that Zone.

Your use case makes a difference, though. Are you loading all of your Zones at once? Did you want to load all of the Sections for all of your Zones at once as well? Or are you just getting the Sections for one or a few Zones at a time?

Upvotes: 1

Jahirul Islam Bhuiyan
Jahirul Islam Bhuiyan

Reputation: 799

    { "Zones": [ { "zone_title":"New zone 1" , "width": 0, "height" : 0, "order" : 0, "sections": [ 
{"section_title": "New section 1", "content" : "Some texts", "order": 0}, 
{"section_title": "New section 2", "content" : "Some texts", "order": 0} ] },  
{ "zone_title":"New zone 2" , "width": 0, "height" : 0, "order" : 0, "sections": [ 
{"section_title": "New section 3", "content" : "Some texts", "order": 0} ] },  
{ "zone_title":"New zone 3" , "width": 0, "height" : 0, "order" : 0, "sections": [{}] }  ] }

Upvotes: 0

Related Questions