Reputation: 42009
I have a link (with class .story) in a navbar, which, if clicked, renders a story template into a canvas div to provide information to the user. I want to give the user the option to remove the template after reading the info, however, I can't set a click event on the delete "x" in the template.
I think I know the problem. My StoryView el is the <div id="story">
so I can set events on anything within that, but since it renders into another div not attached to that view, I can't remove it from that view.
Here's a fiddle showing the problem. Update, I had included the wrong fiddle. Fixed now.
http://jsfiddle.net/mjmitche/RRXnK/145/
Html
<div id="story">
<a href="#" class="story">click this story link to render into canvas_id but how to set event to remove?</a>
</div>
<div id="canvas_id"></div>
View
var StoryView = Backbone.View.extend({
el: $("#story"),
events: {
'click .story': 'render',
'click .delete': 'test'
},
initialize: function() {
},
render: function(){
var template = $('#story_template').html();
this.template = _.template(template);
$('#canvas_id').html(this.template());
},
test: function() {
alert("delete");
<!-- click .delete event not triggering -->
},
remove: function(){
alert("how to remove the template");
<!-- how to remove template after rendering -->
}
});
var story_view = new StoryView();
Template:
<div id="story">
<a href="#" class="story">click this story link to render into canvas_id but how to set event to remove?</a>
</div>
<div id="canvas_id"></div>
<script id="story_template" type="text/underscore">
"I want to make the x
after this story clickable to remove the template
but since it's not within the #story div (which
is just a navbar in my real app), it's not working"
<span class="delete">X</span>
</script>
Upvotes: 1
Views: 91
Reputation: 11003
To understand why you can only listen to events on your view's el, you need to first understand how backbone.js listens to events.
In backbone.js events are delegated (using jQuery or Zepto) to the view's el
. In your case being that your view's el
is #story
your remove event isn't being triggered.
What you can do is when you click to render your template, you can reassign your view's el using setElement which will also move (re-delegate) the views delegated events to the new el
( (as @muistooshort pointed out).
For example
render: function(){
var template = $('#story_template').html();
this.template = _.template(template);
$('#canvas_id').html(this.template());
this.setElement($('#canvas_id'));
},
And in your remove event you can reassign your el
back to the #story
element.
update jsFiddle
Upvotes: 2