当用户单击作为视图一部分的div
with 类时,将触发一个函数。该函数必须从属于该视图的模型中获取属性,该模型的元素已被单击,并将其通过 发送到服务器端。.photo_container
PhotoListView
sendSelectedPhotoId
photo_id
Photo
div .photo_container
fetch()
问题:到目前为止,我设法在单击sendSelectedPhotoId
时触发了该功能div
,但我不知道如何获取视图模型的photo_id
属性。Photo
我应该如何实现这一目标?
在旁注中,我不确定是否photo_id
会发送正确的。
代码
$('#button').click( function() {
// Retrieve photos
this.photoList = new PhotoCollection();
var self = this;
this.photoList.fetch({
success: function() {
self.photoListView = new PhotoListView({ model: self.photoList });
$('#photo_list').html(self.photoListView.render().el);
}
});
});
模型与收藏
// Models
Photo = Backbone.Model.extend({
defaults: {
photo_id: ''
}
});
// Collections
PhotoCollection = Backbone.Collection.extend({
model: Photo,
url: 'splash/process_profiling_img'
});
意见
// Views
PhotoListView = Backbone.View.extend({
tagName: 'div',
events: {
'click .photo_container': 'sendSelectedPhotoId'
},
initialize: function() {
this.model.bind('reset', this.render, this);
this.model.bind('add', function(photo) {
$(this.el).append(new PhotoListItemView({ model: photo }).render().el);
}, this);
},
render: function() {
_.each(this.model.models, function(photo) {
$(this.el).append(new PhotoListItemView({ model: photo }).render().el);
}, this);
return this;
},
sendSelectedPhotoId: function() {
var self = this;
console.log(self.model.get('photo_id'));
self.model.fetch({
data: { chosen_photo: self.model.get('photo_id')},
processData: true,
success: function() {
}});
}
});
PhotoListItemView = Backbone.View.extend({
tagName: 'div',
className: 'photo_box',
template: _.template($('#tpl-PhotoListItemView').html()),
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.close, this);
},
render: function() {
$(this.el).html(this.template( this.model.toJSON() ));
return this;
},
close: function() {
$(this.el).unbind();
$(this.el).remove();
}
});
第二次尝试
我还尝试将事件处理程序放置sendSelectedPhotoId
在PhotoListItemView
我设法正确获取模型属性的位置,但我无法弄清楚当集合执行 fetch()时如何触发reset
事件。PhotoList
看法
PhotoListItemView = Backbone.View.extend({
tagName: 'div',
className: 'photo_box',
events: {
'click .photo_container': 'sendSelectedPhotoId'
},
template: _.template($('#tpl-PhotoListItemView').html()),
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.close, this);
},
render: function() {
$(this.el).html(this.template( this.model.toJSON() ));
return this;
},
close: function() {
$(this.el).unbind();
$(this.el).remove();
},
sendSelectedPhotoId: function() {
console.log('clicked!');
var self = this;
console.log(self.model.get('photo_id'));
self.model.fetch({
data: { chosen_photo: self.model.get('photo_id')},
processData: true,
success: function() {
$(this.el).html('');
}});
}
});
问题:有了这个,我似乎无法在执行in 函数reset
后触发模型的事件,这意味着我无法使用's重新渲染它。fetch()
sendSelectedPhotoId
PhotoListView
render()
sendSelectedPhotoId
在下面来自 Chrome 的 javascript 控制台的屏幕截图中,我在完成它之后打印了集合fetch()
,似乎 fetched将新数据添加到现有模型中,而不是创建 2 个新模型并删除所有现有模型!