I have a view that contains nested views of the same type. Because of this, my delegateEvents
selector needs to be careful to only select the top-level elements and not the elements in the child views.
The following code, used within the context of my view, successfully selects the element I wish to bind:
var $link = this.$('> .node > .indent > a'); // success!
The delegateEvents
object, using the same selector, does not hook up the event at all:
events: {
'click > .node > .indent > a': 'toggleGrouped' // fail :(
}
Note that I have confirmed that the event hookup does work with other, simpler selectors, so it's not an issue with rendering.
What am I doing wrong?
It probably has to do with jQuery's delegate
event not liking the > .node > .indent > a
selector.
You can confirm this by adding the following line of code in your view's render method. (this is what Backbone is doing in delegateEvents
)
$(this.el).delegate('> .node > .indent > a', 'click', this.toggleGrouped);
If it still doesn't work then the issue has to do with the delegate
event and not backbone.
A workaround is to bind to the click event after all the rendering is done in the render method.
this.$('> .node > .indent > a').click(this.toggleGrouped);
You will also have to bind the context of toggleGrouped
in the initialize method since it's no longer being automatically bound.
initialize: function() {
_.bindAll(this, 'toggleGrouped');
}
Found the answer. delegateEvents
uses jQuery.delegate()
, which for some reason doesn't accept selectors that start with a child descender:
http://api.jquery.com/delegate/#comment-66006048
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With