In a Backbone.js template, templates/nutrients/show_template.jst.ejs, I have this:
<div id="nutrient_container">
<table class="person_nutrients">
...
<% for(var i=0; i < person[nutrientsToRender]().length; i++) { %>
<% var nutrient = y[x[i]]; %>
<tr class="deficent_nutrients">
<td>
<span class="nutrient_name"><%= I18n.t(nutrient.name) %></span>
</td>
<td><a id="show_synonyms" href="#"><%= I18n.t("Synonyms") %></a></td>
<% } %>
</table>
</div>
Then, in the Backbone.js view, views/nutrients/show_view.js, I have this:
el: 'table.person_nutrients',
parent_el: 'div#nutrient-graphs',
template: JST["backbone/templates/nutrients/show_template"],
initialize: function(options) {
...
this.render()
},
events: {
'click a#show_synonyms':'synonyms_event'
},
render: function() {
...
$(this.parent_el).append(this.template({person: this.model_object, nutrientsToRender: this.nutrientsToRender(), x: x_prep, y: y_prep}))
},
synonyms_event: function(event) {
alert("I got called");
}
Why doesn’t the event (the alert box) get triggered? I click the link for “Synonyms” and all I get is the root url with a # after it. Why doesn’t the Javascript match up?
I think you are misunderstanding the way a view’s el works.
In backbone.js views always reference a DOM element which is its
el, this DOM element can either be an existing element in the page’s DOM or it can be a new element that does not exist on the DOM.The way views in backbone.js listen to events is by delegating (binding) them to its el. If a view’s el changes, or you want to change what events it listens to you can also manually (re)delegate the events by calling the delegateEvents method
There are two common patterns with views, one is where a view references an existing element on the DOM (this is done by specifying it’s el property or passing in an el when it’s instantiated), and the second is where the view’s el doesn’t reference an existing element on the DOM and instead renders some HTML in it’s el which is then inserted into the DOM.
Very often what’s done is that you have one parent view (often a collections view) which references an existing element on the DOM, and then a bunch of child view’s whose el gets appended.
In your case you probably want to split up your view into a parent view that references a higher container div, and have the child views’ els appended into it.
For example