[英]Backbone View Events are not Firing
我擴展了一個模態對話框類,以顯示帶有一些按鈕的表單。 這是ModalView視圖:
App.ModalView = Backbone.View.extend({
events: {
"click .dismiss": "dismiss"
},
element: "<section class='modal'><div class='overlay'></div><div class='content'></div></section>",
initialize: function () {
this.el = $(this.element);
this.setupElement();
this.bindContext();
this.extendEvents();
this.render();
this.miscellaneous();
},
bindContext: function () {
_.bindAll(this, "dismiss", "render", "setBoxStyle");
},
setupElement: function () {
this.template = $("#modal-template");
},
miscellaneous: function () {},
extendEvents: function () {},
render: function () {
$(this.el).find(".content").html(this.template.html());
$("body").append(this.el);
this.setBoxStyle();
if (this.options.content) {
$(this.el).find(".content").html(this.options.content);
}
},
getMargin: function (width, height) {
var top, left;
width = parseFloat(width);
height = parseFloat(height);
top = Math.max(0, Math.round((window.innerHeight - height) / 2));
left = Math.max(0, Math.round((window.innerWidth - width) / 2));
return top + "px " + left + "px";
},
setBoxStyle: function () {
var css = this.options.css || {};
var el = $(this.el).find(".content");
el.css(css);
var width = el.outerWidth();
var height = el.outerHeight();
css.margin = this.getMargin(width, height);
el.css(css);
},
dismiss: function () {
this.remove();
}
});
這是擴展視圖:
App.AddRecordView = App.ModalView.extend({
setupElement: function () {
this.template = $("#add-record-template");
}
});
這是模板:
<script type="text/template" id="add-record-template">
<h1>Add Record</h1>
<button class="green save">Save Record</button>
<button class="cancel dismiss">Cancel</button>
</script>
這是我初始化視圖的方式:
this.addRecordView = new App.views.addRecord({
model: this.model,
css: {
width: "400px"
}
});
出於某種原因,當我單擊按鈕時,dismiss事件永遠不會觸發。 這里發生了什么?
您尚未為視圖定義el或tagName。 如果未聲明上述任何一項,則Backbone默認將委托事件分配給div。 然后,在您的Initialize函數中,顯式設置el,並用附加的事件處理程序覆蓋el。 嘗試將您的部分設置為tagName並將其從element屬性中刪除。 然后將您的元素附加到this.el。 抱歉,沒有提供代碼示例,但我在手機上書寫。
沒有正確的代碼,我只能猜測,但是這種錯誤通常是因為在dom准備好之前就聲明了視圖的代碼。
您能告訴我們您在哪里啟動應用程序嗎?
是在jQuery文檔准備功能?
$(function(){
this.addRecordView = new App.views.addRecord({
model: this.model,
css: {
width: "400px"
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.