如何获取对在事件处理程序中生成事件的ImageListItemView的引用?
addOne: function(image){
var imageListItemView = new ImageListItemView({model: image});
imageListItemView.on('imageListItemView:click', this.itemViewClick, this)
imageListItemView.render();
this.$el.append(imageListItemView.el);
},
itemViewClick: function(){
//Get reference to ImageListItemView that originated event
}
这是ImageListItemView:
// ImageListItemView
//-------------------------------------------------------------------------------//
window.ImageListItemView = Backbone.View.extend({
initialize: function(){
this.model.on('change', this.render, this);
this.model.on('destroy hide', this.remove, this);
this.model.on('image:selectionChange', this.select, this);
},
events : {
"click" : "onClick"
},
className: 'item_view',
template: _.template($('#image_list_item_view_template').html()),
render: function(){
this.$el.html(this.template(this.model.toJSON()));
if(this.model.selected){
this.$el.addClass('selected');
}else{
this.$el.removeClass('selected');
}
},
remove: function(){
this.$el.remove();
},
select: function(){
this.render();
},
onClick: function(e){
this.trigger('imageListItemView:click');
}
})
这是ImageListView:
// ImageListView
//-------------------------------------------------------------------------------//
window.ImageListView = Backbone.View.extend({
className: 'image_list_view',
tagName: 'nav',
initialize: function(){
this.collection.on('add', this.addOne, this);
this.collection.on('reset', this.addAll, this);
},
render: function(){
this.addAll();
return this;
},
addAll: function(){
this.$el.empty();
this.collection.forEach(this.addOne, this);
},
addOne: function(image){
var imageListItemView = new ImageListItemView({model: image});
imageListItemView.on('imageListItemView:click', this.itemViewClick, this)
imageListItemView.render();
this.$el.append(imageListItemView.el);
},
itemViewClick: function(e){
//Get reference to ImageListItemView that originated event
//e is undefined
//this.collection.setSelectedImage(this.model);
}
})
答案 0 :(得分:0)
好吧,我不是Backbone的专家,但您是否尝试过替换事件上下文?
即
imageListItemView.on('imageListItemView:click', this.itemViewClick, imageListItemView);
如果我理解正确,this
内的itemViewClick
应该引用ImageListItemView
。
值得一试。