user3214296 user3214296 - 5 months ago 52
HTML Question

Backbone.js click event in a Modal Reveal

I got a Modal Reveal (http://foundation.zurb.com/docs/components/reveal.html) in a template and in this modal I got a form with a button and I want to listen to this button in the view but when I click it doesn't fire anything.
here is my code :

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(){
...
}


I think the problem is that the view can't find the button in the el.

Answer

Event's in backbone views work using event delegation, that is when you specify an events hash backbone binds those events to the root el. In this case your problem is that the modal popup isn't actually a descendent of the root el (the plugin attaches it elsewhere in the DOM, you can inspect the element in firebug/web inspector to see this yourself).

What you can do is bind the event manually yourself, for example

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;
},
Comments