Manh Ha
Manh Ha

Reputation: 1857

How to add a collection-bound select box to a form in Backbone.Marionette?

I have a member form in which there is a select box for choosing a group of this member.

I'm using Backbone & Backbone.Marionette. The member form is bound to a MemberModel. Data for the select box comes from a GroupCollection. MemberModel contains only a group_id, not any reference to a GroupCollection.

I'm now generating this select box manually (fetch GroupCollection then add to select box by using Javascript).

I would like to know if there is a better way to do it in Backbone.Marionette. I thought it could be done with ListView and ItemView but I couldn't know how to add the select box to this Member form because this form is not a Layout.

Upvotes: 2

Views: 3019

Answers (1)

Derick Bailey
Derick Bailey

Reputation: 72868

There's many different ways that this could be done, and a CollectionView could be used. You would have to set the CollectionView's tagName to "select" and then the itemView used with the CollectionView would have a tagName set to "option".

The easier idea might be to use an ItemView on it's own, with your collection as the data source. You can use a collection with an ItemView no problem, you just have to do the loop in your template.

Using underscore.js templates:

<script type='text/template' id='some-template'>
  <select>
    <%= _.each(items, function(item){ %>
    <option value="<%= item.value %>"><%= item.name %>
    <%= }) %>
  </select>
</script>

Marionette.ItemView.extend({
  template: "#some-template"
  // ...
})

I wrote about these two basic options in more detail, here: http://lostechies.com/derickbailey/2011/10/11/backbone-js-getting-the-model-for-a-clicked-element/

Hope that helps.

Upvotes: 5

Related Questions