2014-02-26 41 views
2

我在模板中获得了Modal Reveal(http://foundation.zurb.com/docs/components/reveal.html),在这种模式下,我得到了一个带有按钮的窗体,我想在视图中听这个按钮,但是当我点击它时不发射任何东西。 这里是我的代码:Backbone.js在Modal Reveal中点击事件

的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">&#215;</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中找到按钮。

回答

4

事件在骨干视图中使用事件委托来工作,即当您指定事件哈希主干将这些事件绑定到根el。在这种情况下,你的问题是模式弹出并不是实际上是根的后代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; 
}, 
2

即使有已是一个正确的答案,我想补充一点,如果你从骨干中打开模式查看返回对新元素的引用。

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">&#215;</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(){ 
    ... 
} 
+0

这是一个清洁的解决方案。谢谢! – codebreaker

+0

基金会6有任何更新吗?这似乎不再有效。 – user1801879