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:
1 2 3 4 5 6 7 8 9 10 11 12 | |
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.
1 2 3 4 5 | |
Usage
Here is fully functional MarionetteJS sample application on JSFiddle
But generally there are two simple steps for setting up SelectView:
Instantiate the select view within collection entities:
var selectView = new SelectView({ collection: collection });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 | |