gpt4 book ai didi

javascript - 使用更多属性更新模型 (backbone.js)

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:20:04 26 4
gpt4 key购买 nike

我有一个包含图像 productView 列表 productListView 的页面。 productListView 绑定(bind)到包含模型 product 的集合 productList。单击图像时,会出现一个模态 ModalView,其中包含有关其照片被单击的产品的更多详细信息。

问题:为了尽量减少传输给用户的数据,当页面和 productListView加载。单击 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 来绑定(bind) 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 不能为您提供一切,请将 fetch 替换为可以做到的 ajax 调用。

关于您的更新:success 回调上下文中的thiswindow。您想改用保存的 self

关于javascript - 使用更多属性更新模型 (backbone.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12267578/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com