我有一個包含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
感謝Eru,但這沒有任何區別。根據我的理解,爲了發起一個事件,沒有必要有一個「el」或者一個特定的id。 – tmaximini
你需要el以便骨幹綁定事件 –