我有以下 backbone.js 代码,用于呈现后端提供的产品列表。
问题是 AppView
的 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
事件。
关于javascript - Backbone.js 事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20314720/