jmasterx
jmasterx

Reputation: 54113

CompositeView where children can come from multiple collections

Here is what I need in a nutshell.

I need to show a dropdown/combobox where the children can come from many collections. All these collections' models have a text attribute which I will show in the dropdown.

I am wondering if it is possible to create the dropdown's list from many collections.

Namely:

Collection one has:
Text: A, Fungus: 9
Text: B, Fungus: 7
Text: C, Fungus: 6

Collection 2 has:
Text: Q, NumberOfBugs: 8
Text: R, NumberOfBugs: 9
Text: S, NumberOfBugs: 7

The list for my dropdown ends up looking like:

<option>A</option>
<option>A</option>
<option>A</option>
<option>Q</option>
<option>R</option>
<option>S</option>

So that if I select A, I want to be able to get A's model with the Fungus attribute, and if I select R I want R's model which has the NumberOfBugs attribute.

The idea is they are 2 collections with common attributes, but in the backend correspond to different models.

Is there some way to do this in Marionette/Backbone?

Some way to create a dropdown that has multiple data sources / collections?

Merging into one collection will not work because sync / fetch operations will not work correctly.

Upvotes: 1

Views: 47

Answers (1)

maxlath
maxlath

Reputation: 1841

if those collection always work together in your application, you could make them a single collection from start and then use subcollections using something like backbone-filtered-collection for custom behaviors and sync / fetch: models added to a subcollection would be also added to the general one.

var general = new Backbone.Collection
var fungus = new FilteredCollection(general)
var bugs = new FilteredCollection(general)

fungus.filterBy(function(model){
  return model.has('fungus')
})

bugs.filterBy(function(model){
  return model.has('numberOfBugs')
})

general.add([
    {text: 'A', fungus: 9},
    {text: 'B', fungus: 7},
    {text: 'C', fungus: 6},
    {text: 'Q', numberOfBugs: 8},
    {text: 'R', numberOfBugs: 9},
    {text: 'S', numberOfBugs: 7}
  ])



// general.length => 6
// fungus.length => 3
// bugs.length => 3

hope it helps

Upvotes: 1

Related Questions