Skip to content

Instantly share code, notes, and snippets.

@gillesruppert
Created June 27, 2013 10:44
Show Gist options
  • Save gillesruppert/5875554 to your computer and use it in GitHub Desktop.
Save gillesruppert/5875554 to your computer and use it in GitHub Desktop.
Marionette.CollectionView for a select box
<select> // CollectionView.el
<option value="modelId">Model.name</option> // ItemView for the model
</select>
<!--
can you have Marionette views that do not have a template without overriding the render method? Overriding the render method is painful as you have to implement the `isClosed setting plus all the event triggers, so it keeps working with all the Marionette hooks, or am I mistaken?
-->
@gillesruppert
Copy link
Author

Ok, I think I've worked around this:
instead of using a Marionette.ItemView, I'm using a very basic Backbone.View that has a simple render method which just sets the value and innerText of the view.el. This delivers the result as expected.

If however you think there is a better way, please let me know!

@mxriverlynn
Copy link

if you really want to use marionette for this, don't use a collectionview. the option tag is very simple, and trying to get an ItemView to render each tag is a big waste, honestly. too much code for no benefit.

you could do it this way, instead:

<script id="select-template" type="text/html">
  <% _.each(items, function(item){ %>
    <option value="<%= id %>"><%= name %></option>
  <% }) %>
</script>
var SelectView = Marionette.ItemView({
  template: "#select-template",
  tagName: "select"
});

var c = new MyCollection();
// load your data here

var sv = new SelectView({
  collection: c
});

someRegion.show(sv);

@shawninder
Copy link

Where does items come from?

@mostafiz57
Copy link

Hello derickbailey,
Your code is very much excellent, but has one small mistake , You miss item ..
html code looks like this .

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

@kyanny
Copy link

kyanny commented Apr 9, 2015

Same solution, well explained. http://stackoverflow.com/a/18194457/374851

An ItemView can take a collection in to it, and you can access that collection at items inside of the template.

and it's written in document too.
https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.itemview.md#rendering-a-collection-in-an-itemview

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment