[英]Updating Model with more attributes (backbone.js)
我有一個頁面,其中包含圖像productView
的列表productListView
。 productListView
綁定到包含模型product
的集合productList
。 單擊圖像時,將出現模態ModalView
其中包含有關單擊了照片的產品的更多詳細信息。
問題:為了最小化傳輸給用戶的數據,在加載頁面和productListView
時僅fetch
了產品的少數屬性。 當單擊productListView
中的照片時,如何更新具有更多屬性(例如,很長的描述)的模型product
?
模型
Product = Backbone.Model.extend({
url: '/api/product' // Gets FULL details of product
});
采集
ProductCollection = Backbone.Collection.extend({
url: '/api/products' // Gets MINIMAL details of product
})
視圖
ProductListView = Backbone.View.extend({
el: '#photo_list',
initialize: function() {
this.collection.bind('reset', this.render, this);
},
render: function() {
this.collection.each(function(photo, index) {
$(this.el).append(new ProductView({ model: photo }).render().el);
}
return this;
},
});
ProductView = Backbone.View.extend({
tagNAme: 'div',
template: _.template( $('#tpl_ProductView').html() ),
events: {
'click .photo': 'showModal',
},
render: function() {
$(this.el).html( this.template( this.model.toJSON() ) );
return this;
},
// Creates the Modal View with FULL details of the product
showModal: function() {
modalView = new ModalView({ model: this.model });
}
});
模態視圖
ModalView = Backbone.View.extend({
el: $('#modal'),
template: _.template( $('#tpl_modal').html() ),
initialize: function() {
this.render();
},
render: function() {
$(this.el).show().append( this.template( this.model.toJSON( this.model ) ) );
},
});
我收到錯誤Uncaught TypeError: Object [object Window] has no method 'render'
。 即使我正在使用_.bindAll
綁定render
為什么也如此? 我知道var self=this
可以工作,但是_.bindAll
為什么不呢?
initialize: function() {
_.bindAll(this, 'render');
var self = this;
// Update Model with Full details
this.model.fetch({
data: {post_id: this.model.get('id')},
processData: true,
success: function() {
// The usual renders
this.render();
}
});
如果您的Product.fetch
調用獲取了完整的模型(具有擴展的屬性),則更改showModal
以執行此操作,然后呈現:
showModal: function() {
var modalView = new ModalView({ model: this.model }),
p = this.model.fetch();
p.done(modalView.render);
}
和
ModalView = Backbone.View.extend({
el: $('#modal'),
template: _.template( $('#tpl_modal').html() ),
render: function() {
this.$el.show().append( this.template( this.model.toJSON() ) );
},
});
如果fetch不能為您提供一切,那么請用提供的ajax調用替換fetch。
至於更新: this
在success
回調上下文是window
。 您想使用保存的self
。
在此代碼中,應使用self.render();
代替this.render()
initialize: function() {
_.bindAll(this, 'render');
var self = this;
// Update Model with Full details
this.model.fetch({
data: {post_id: this.model.get('id')},
processData: true,
success: function() {
// The usual renders
self.render();
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.