【发布时间】:2014-08-09 05:10:12
【问题描述】:
考虑下面的代码。如果我在选择视图中创建一个更改事件处理程序,那么在不分配选项视图中的 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;
}
});
【问题讨论】:
-
@AnatoliyZaslavskiy,如果事件发生在期权级别,我会同意你的看法。但是,更改事件仅发生在 Select 级别,而不发生在 Option 级别。所以集合视图,它是一个选择视图,会监听更改事件。我怎么知道选择了哪个型号?我将 data-cid 分配给所有选项并通过 cid 获取模型,但是我不喜欢那样。它违背了使用像 Backbone 这样的 MV 框架的目的。我根本不想用dom,坚持model。
-
When the select event happens on the ItemView you reference the model: `events: {
-
当 select 事件在 DOM 中发生时,ItemView 订阅它并触发
selected事件或在创建视图时传入的关联模型this.model上设置selected属性.无需 CID。如果您设置了一个属性,您可以随时返回并在集合上执行findWhere。如果你做一个触发器,你可以像丹尼尔建议的那样做一个listenTo。 -
是的,但是点击事件永远不会在选项模型视图中触发。更改事件仅在选择集合视图中触发。 jsfiddle.net/7cfjznjn