[英]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.