[英]Backbone.js click event in a Modal Reveal
我在模板中有一個Modal Reveal( http://foundation.zurb.com/docs/components/reveal.html ),在此模式下,我有一個帶有按鈕的表單,我想在視圖中收聽此按鈕,但是當我單擊它不會觸發任何操作。 這是我的代碼:
index.html :
<body>
<div class="page">
<div id="content"></div>
</div>
</body>
tplGroups.html :
<div id="myModal" class="reveal-modal small" data-reveal>
<label>Name :</label>
<input type="text" id="inNameGroup"></input>
<label > Description :</label>
<textarea id="inDescriptionGroup"></textarea>
<button class="button right" id="btnAddGroup">Add group</button>
<a class="close-reveal-modal">×</a>
</div>
<div class="row">
<button class="button tiny right" data-reveal-id="myModal" data-reveal>Add</button>
</div>
group.js :
el: "#content",
initialize: function(){},
render:function(){
this.template = _.template(tpl.get('tplGroup'));
this.$el.html(this.template(this.model.attributes));
this.$el.i18n();
return this;
},
events:{
"click #btnAddGroup": "addGroup"
},
addGroup: function(){
...
}
我認為問題在於視圖無法在El中找到按鈕。
骨干視圖中的事件使用事件委托進行工作,也就是說,當您指定事件哈希骨干時,會將這些事件綁定到根el
。 在這種情況下,您的問題是模式彈出窗口實際上不是root el
的后代(插件將其附加到DOM
其他位置,您可以在firebug / web inspector中檢查該元素以自己查看)。
您可以做的是自己手動綁定事件,例如
render:function(){
this.template = _.template(tpl.get('tplGroup'));
this.$el.html(this.template(this.model.attributes));
this.$el.i18n();
$('#btnAddGroup').on('click', this.addGroup);
return this;
},
即使已經有一個正確的答案,我也想補充一點,如果您在“主干”視圖中打開模態,它將返回對新元素的引用。
var modalElement = this.$('#myModal').foundation('reveal', 'open');
可以使用setElement()
方法將元素的引用應用於視圖,該方法將創建緩存的$el
引用,並將視圖的委托事件從舊元素移到新元素。
tplGroups.html:
<div id="myModal" class="reveal-modal small" data-reveal>
<label>Name :</label>
<input type="text" id="inNameGroup"></input>
<label > Description :</label>
<textarea id="inDescriptionGroup"></textarea>
<button class="button right" id="btnAddGroup">Add group</button>
<a class="close-reveal-modal">×</a>
</div>
<div class="row">
<button class="button tiny right" id="btnOpenModal">Add</button>
</div>
group.js:
el: "#content",
initialize: function(){},
render:function(){
this.template = _.template(tpl.get('tplGroup'));
this.$el.html(this.template(this.model.attributes));
this.$el.i18n();
return this;
},
events:{
"click #btnOpenModal": "openModal",
"click #btnAddGroup": "addGroup"
},
openModal: function(){
this.setElement(this.$('#myModal').foundation('reveal', 'open'));
},
addGroup: function(){
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.