我有一个Marionette CollectionView,它将ItemView呈现为<select>
菜单,每个ItemView呈现为<option>
。我的问题是,当我在CollectionView上调用'change'事件(意味着用户选择了一个选项)时,如何从ItemView中获取所选<option>
的模型?
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
}
});
答案 0 :(得分:5)
最干净的方法是将option
标记与相应模型的ID一起呈现为值:<option value="42">Forty Two</option>
。然后,在更改时,获取该值并使用它通过ID collection.get(id)
从集合中检索模型。像option
这样的元素有一个自然属性,可以作为模型ID,但对于其他元素,您可以使用data-id="42"
属性。
另一种可行的方法,虽然我认为不如上面那么简单和干净,但是使用jQuery的.data
方法或等效方法将模型实例与元素相关联。
答案 1 :(得分:2)
无需添加自定义ID等等,并且danmactough的答案也不起作用,所以最好忽略它。即使是木偶的childEvents
,也无法使用select / option标签。
我的方法是绑定change
上的CollectionView
事件,并匹配集合中的模型索引和下拉列表中的:selected
元素:
var listView = Marionette.CollectionView.extend({
itemView: singleView,
tagName: 'select',
id: 'my-selector',
events: {
'change': 'optionSelected'
},
optionSelected: function() {
// The selected model:
var model = this.collection.at($(':selected', this.$el).index()));
}
});
答案 2 :(得分:0)
我认为更好的,特定于Marionette的解决方案是使用modelEvents
或collectionEvents
配置哈希available in a CollectionView or CompositeView。
var listView = Marionette.CollectionView.extend({
itemView: singleView,
tagName: 'select',
id: 'my-selector',
modelEvents: {
'change': 'modelChanged'
},
modelChanged: function(e) {
// "e" is the event
// "this" is the ItemView
// "this.model" is the model
}
});