Search code examples
javascriptbackbone.jsmarionette

How do I get the model for the selected <option> in a Marionette.js CollectionView?


I have a Marionette CollectionView that renders an ItemView into a <select> menu, with each ItemView rendering as an <option>. My question is, when I call the 'change' event on the CollectionView (meaning the user has selected an option), how do I get the model of the selected <option> from the ItemView?

var singleView = Marionette.ItemView.extend({
        template: '#optionTemplate',
        tagName: 'option'
    });

var listView = Marionette.CollectionView.extend({
        itemView: singleView,
        tagName: 'select',
        id: 'my-selector',
        events: {
            'change': 'optionSelected'
        },
        optionSelected: function() {
          // I need to get the model from within this function

        }
    });

Solution

  • The cleanest approach is to render the option tag with the ID of the corresponding model as the value: <option value="42">Forty Two</option>. Then, on change, get that value and use it to retrieve the model from the collection by ID with collection.get(id). Some elements like option have a natural attribute that makes sense to be the model ID, but for other elements you can just use a data-id="42" attribute.

    Another approach that is viable although I think less simple and clean than the above would be to use jQuery's .data method or equivalent to associate the model instance with the element.