请考虑以下代码.如果我在选择视图中创建更改事件处理程序,那么获取选项视图的所选模型的最简洁和最好的方法是什么,而不在选项视图中指定data-cid属性.我试图保持dom的真相,并采取这种Backbone方式:
var ItemView = Backbone.View.extend({
tagName: 'option',
initialize:function(){
this.template= _.template($('#menu_item_view').html());
},
render:function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var CollectionView = Backbone.View.extend({
tagName: 'select',
initialize:function(){
this.collection = new ItemCollection();
this.collection.on('sync',this.render,this);
this.collection.fetch();
},
render:function(){
this.$el.html(this.collection.map(function( item ){
return new ItemView ({model:item}).render().el;
},this);
return this;
}
});
Run Code Online (Sandbox Code Playgroud)