我在模板中得到了一个模态显示(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中的按钮。
答案 0 :(得分:4)
主干视图中的事件使用事件委派,即当您指定事件时,哈希主干将这些事件绑定到根el
。在这种情况下你的问题是模态弹出窗口实际上不是根el
的后代(插件将它附加到DOM
的其他位置,你可以检查firebug / web检查器中的元素以查看这个你自己)。
您可以自己手动绑定事件,例如
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;
},
答案 1 :(得分:2)
即使已经有一个正确的答案,我想补充一点,如果你从Backbone视图中打开模态,它会返回对新元素的引用。
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(){
...
}