Simple SelectView: Triggers Event and Returns Model When Chosen

In this post I’d like to share the code snippet which I recently used to represent Backbone.Collection as a HTML select Tag within MarionetteJS application.

Here is SelectView which is a kind of ItemView and responsible to render options and trigger the event when one is chosen:

SelectView
1
2
3
4
5
6
7
8
9
10
11
12
var SelectView = Marionette.ItemView.extend({
    template: "#options-template",
    tagName: "select",

    events: {
        'change' : 'optionSelected'
    },

    optionSelected: function(e){
        this.trigger('item:chosen', this.collection.get(e.target.value));
    }
});

And below is #options-template where items is an array of objects which comes from the collection we’ll pass to the SelectView, i.e. collection.toJSON() which is a common behaviour when you pass collection to the ItemView.

NOTE: passing both collection and model at the same time won’t work, because model has precedence.

#options-template
1
2
3
4
5
<script type="text/html" id="options-template">
    <% for (i = 0; i < items.length; i++) { %>
        <option value="<%= items[i].id %>"><%= items[i].value %></option>
    <% } %>
</script>

Usage

Here is fully functional MarionetteJS sample application on JSFiddle

But generally there are two simple steps for setting up SelectView:

  1. Instantiate the select view within collection entities:

     var selectView = new SelectView({
         collection: collection
     });
    
  2. Setup event listener to get updates when model is chosen:

     this.listenTo(selectView, 'item:chosen', function(model){
         // do something with your model, e.g.
         alert('Model ID: ' + model.get('id') + ' is chosen!');
     });
    

And the rest is pretty common workflow, for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 1. Instantiate Backbone Collection
var collection = new Backbone.Collection([
    {id: 1, value: 'Option1'},
    {id: 2, value: 'Option2'},
    {id: 3, value: 'Option3'}
]);

// 2. Instantiate select view
var selectView = new SelectView({
    collection: collection
});

// 3. Setup event listener
this.listenTo(selectView, 'item:chosen', function(model){
    // do something with your model, e.g.
    alert('Model ID: ' + model.get('id') + ' is chosen!');
});

// 4. Render the select view to particular region
this.region.show(selectView);

Comments