我正在通过模态窗口进行ajax文件上传,并在帖子中预览。每个帖子都有自己的模型和视图。模态窗口也是一个单独的视图,绑定到现有的DOM元素。
点击帖子视图中的Attach
按钮时,我从模态视图调用.open(),将模型视图作为设置传递给模态视图:
POST VIEW:
======================
ModalAttach.open({
postModel : this.model
});
当上传模态视图中的文件时,我将服务器响应添加到传递的Post模型中以便稍后在帖子中作为预览呈现它:
MODAL VIEW:
======================
// file upload success
success: function(data) {
// if it's first call, set []
var imagesUploaded = self.postModel.get('images_uploaded') || [];
// add server response to array
imagesUploaded.push(data);
// rewrite current model array to new array
self.postModel.set({ 'images_uploaded' : imagesUploaded });
}
要在帖子中进行预览(在真正提交之前),我有一个功能
POST VIEW:
======================
renderUploadedImages: function () {
var self = this;
this.$uploadedImagesWrapper = this.$('.b-uploaded__images');
if (this.model.get('images_uploaded')) {
this.$uploadedImagesWrapper.empty();
this.model.get('images_uploaded').forEach(function (uploadedImage) {
self.$uploadedImagesWrapper.append(
uploadedImageTemplate({
'source': uploadedImage.source
})
)
});
}
}
为了触发图像渲染,我绑定一个列表器来跟踪模态视图改变model.images_uploaded的时间:
POST VIEW:
======================
initialize: function () {
this.addEvents();
this.renderUploadedImages();
},
addEvents: function () {
var self = this;
this.model.on('change:images_uploaded', function () {
self.renderUploadedImages();
})
},
首次上传时,Post视图中的问题renderUploadedImages()
仅触发一次。其他更改未被捕获(当postModel.get('images_uploaded')。长度变为2,3等等。)。我做错了什么?
感谢。
答案 0 :(得分:0)
当你这样做时:
var imagesUploaded = self.postModel.get('images_uploaded') || [];
// add server response to array
imagesUploaded.push(data);
// rewrite current model array to new array
self.postModel.set({ 'images_uploaded' : imagesUploaded });
第一次,如果您检查self.postModel.get('images_uploaded')
,则会发现undefined
,这就是为什么当您设置它时会触发事件change:images_uploaded
。
但是第二次调用success
方法时你不会改变模型属性,它总是指向同一个对象(数组),你只需更改数组值。