[英]Backbone.js event not fired
我有以下backbone.js代码,用于呈现后端提供的产品列表。 问题是AppView
的render
方法永远不会被调用 - 即通过this.listenTo(product_list, 'change', this.render);
附加的监听器this.listenTo(product_list, 'change', this.render);
fetch
调用完成后不会触发。
谁能告诉我有什么问题?
$(function(){
Product = Backbone.Model.extend({
url: '/api/product',
defaults: {
name: 'default name'
}
});
// Collection
ProductList = Backbone.Collection.extend({
url: '/api/products',
model: Product,
});
product_list = new ProductList();
// Views
ProductListView = Backbone.View.extend({
tagName: 'div',
initialize: function(){
this.listenTo(this.model, 'change', this.render);
},
render: function(){
console.log('p:render');
this.$el.html('<input type="checkbox" value="1" name="' + this.model.get('title') + '" /> ' + this.model.get('title') + '<span>$' + this.model.get('price') + '</span>');
this.$('input').prop('checked', this.model.get('checked'));
return this;
}
});
AppView = Backbone.View.extend({
el: '#list',
initialize: function(){
this.list = $('#list');
this.listenTo(product_list, 'change', this.render);
product_list.fetch({reset:true});
console.log('fetch');
},
render: function(r) {
console.log('AppView.render');
product_list.each(function(product){
console.log('p:e:render()');
var view = new ProductListView({ model: product });
this.list.append(view.render().el);
});
return this;
}
});
new AppView();
});
我遇到了同样的问题,我通过查看源代码发现,当它们获取时,集合不会触发change
事件。 仅在已更新的模型上触发change
事件。 由于您使用reset:true
进行提取,请尝试侦听reset
事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.