【发布时间】:2012-10-31 09:41:36
【问题描述】:
我在 Backbone 中有一个由 GalleryItem 子视图组成的画廊。
我现在遇到的问题是子视图上的事件没有正确触发。
这是我GalleryItemView的代码:
// Gallery View: Displays a Single Image Element
var GalleryItemView = Backbone.View.extend({
el: '#isotope',
events: {
"click .hoverbox": "onHoverBoxClick"
},
initialize: function () {
this.template = Hogan.compile($("#gallery-item-template").html());
},
render: function () {
this.$el.append(this.template.render(this.model.toJSON()));
return this;
},
onHoverBoxClick: function () {
console.log("clicked: ", this.model.id);
}
});
我希望每个元素在单击 .hoverbox div 时都会触发 onHoverBoxClick 事件。
但它什么也没做。
如果我将此添加到视图中:
el: "#mydiv"
然后它会触发事件,但会针对每个 GalleryItemView。 (所以对于 8 个子视图,我得到 8 个 console.logs,我也只点击了一个)
我的子视图模板如下所示:
<script type="text/x-handlebars-template" id="gallery-item-template">
<div class="item {{tags}}" style="width: auto;">
<img class="eveimage" src="{{image_medium_url}}">
<div class="hoverbox down"><span>{{tags}}</span> </div>
</div>
</script>
画廊的收藏视图看起来像这样(这是我实例化画廊项目的地方):
// Gallery View: Displays the main image / project gallery
window.views.GalleryView = Backbone.View.extend({
el: '#isotope_container',
className: 'no-transition',
template: _.template($("#gallery-template").html()),
initialize: function() {
this.collection = new gallery();
this.$el.append(this.template);
this.collection.on('reset', this.render, this);
},
render: function(){
console.log("ich render nei");
this.collection.forEach(this.addOne, this);
},
addOne: function(model){
var itemView = new GalleryItemView({model: model});
var el = itemView.render().el;
this.$el.append(el);
}
});
任何想法为什么会这样?谢谢...
【问题讨论】:
-
我没有看到你的模板,但假设它是视图列表,所以每个
li都有不同的 id 属性。然后调用视图:new GalleryItemView({model: model, el: '#gallery-item-id'})与项目的 id 将委托绑定到这个特定元素 -
感谢 Eru,但这并没有什么不同。据我了解,为了触发事件,实际上没有必要有一个“el”或一个特定的 id。
-
你需要 el 才能让主干绑定事件
标签: javascript backbone.js backbone-views backbone-events