I have a backbone application that gives the user the option to display a map by clicking a button. In the CharactersView, the ‘showMap’ event is set up (triggered by clicking the #map_button) with the corresponding showMap function to display a map once the event’s triggered. The CharactersView also renders the character_template, and the character_template contains the #map_button and the actual map code with the class ‘map.’Everything works fine if the #map_button is located in the same template (the chracters_template) as the map, which gets rendered from CharactersView. However, if I move the #map_button outside of the character_template (for example, into another template or directly into the body of the page), then the showMap event in CharactersView is no longer triggered, and the map no longer gets displayed in the character_template. Note, I am waiting until the characters template gets rendered to the page before I try to click the #map_button and it’s still not working.
From the above description and the code below, can you tell me what the issue here might be and how I might solve it.
Code
Set up event binding in CharactersView so that a map is displayed when a button is clicked
events: {
'click #map_button' : 'showMap'
},
showMap: function(){
$(".map").toggle();
}
The character_template rendered by the characters view. The actual map with the class ‘map’ that gets displayed is in the same template that gets rendered by the characters view.
<script id="character_template" type="text/x-handlebars">
<input class='action_button' id='map_button' type='button' value='Show Map' />
<%= image_tag "http://maps.google.com/maps/api/staticmap?size=300x200&sensor=false&zoom=12&markers={{ latitude }}%2C{{ longitude }}", :class => "map" %>
</script>
If I removed the button from the character_template and put it in another tempalte, the click #map_button event in CharactersView no longer works. It’s also the same result if I just put the button directly in the body of the html.
… other code ommitted…
When you set events in a view using the events hash, Backbone eventually uses jQuery to listen to the event. In Backbone.delegateEvents, you can see this code:
Using
this.$el.on()(where ‘this’ is your view) is only listening for the event within that view’s DOM element ($el is a cached jQuery object).So, if you move the button to another view, you need to add your event listener to that view as well:
Basically, using the views event hash is saying, ‘listen to this event only within this view’s DOM element.’