我从Backbone.View
生成一个下拉列表
将它附加到DOM后,不会触发更改事件。 delegateEvents
没有修复它。有人能告诉我盲点在哪里吗?
模型和集合:
App.Models.DictionaryItem = Backbone.Model.extend({
default: {
key: '',
value: '', id: 0
}
});
App.Collections.Dictionary = Backbone.Collection.extend({
model: App.Models.DictionaryItem,
initialize: function (models, options) {
},
parse: function (data) {
_.each(data, function (item) {
// if(item){
var m = new App.Models.DictionaryItem({ key: item.code, value: item.name });
this.add(m);
// }
}, this);
}
});
查看:
App.Views.ItemView = Backbone.View.extend({
tagName: 'option',
attributes: function () {
return {
value: this.model.get('key')
}
},
initialize: function () {
this.template = _.template(this.model.get('value'));
},
render: function () {
this.$el.html(this.template());
return this;
}
});
App.Views.CollectionView = Backbone.View.extend({
tagName: 'select',
attributes: {
'class': 'rangesList'
},
events: {
'change .rangesList': 'onRangeChanged'
},
initialize: function (coll) {
this.collection = coll;
},
render: function () {
_.each(this.collection.models, function (item) {
this.$el.append(new App.Views.ItemView({ model: item }).render().el);
}, this);
// this.delegateEvents(this.events);
return this;
},
selected: function () {
return this.$el.val();
},
onRangeChanged: function () {
alert('changed');
}
});
渲染:
var coll = new App.Collections.Dictionary(someData, { parse: true });
var v= new App.Views.CollectionView(coll);
var vv=v.render().el;
// new App.Views.CollectionView(coll).render().el;
$('body').append(vv)
答案 0 :(得分:1)
tagName
上的attributes
和CollectionView
:
tagName: 'select',
attributes: {
'class': 'rangesList'
},
说el
将为<select class="rangesList">
。但是你的events
:
events: {
'change .rangesList': 'onRangeChanged'
},
正在视图'change'
内的.rangesList
内部监听el
个事件。来自fine manual:
事件以
{"event selector": "callback"}
格式编写。 [...]省略选择器会导致事件绑定到视图的根元素(this.el
)。
所以你试图从不存在的事物中侦听事件。如果您想直接从视图el
收听事件,请忽略选择器:
events: {
'change': 'onRangeChanged'
}