Backbone.js - why is my delegateEvents switch not working?

I have a view that contains nested views of the same type. Because of this, my delegateEvents selector has to be careful to select only top-level items, not items in child views.

The following code used in the context of my view successfully selects the element I want to bind:

 var $link = this.$('> .node > .indent > a'); // success! 

The delegateEvents object, using the same selector, does not hook the event at all:

 events: { 'click > .node > .indent > a': 'toggleGrouped' // fail :( } 

Note that I have confirmed that event binding works with other, simpler selectors, so this is not a rendering problem.

What am I doing wrong?

+4
source share
3 answers

This is probably due to the jQuery delegate event, which the selector > .node > .indent > a does not like.

This can be confirmed by adding the following line of code to the view rendering method. (this is what Backbone does in delegateEvents )

 $(this.el).delegate('> .node > .indent > a', 'click', this.toggleGrouped); 

If it still does not work, the problem is with the delegate event, and not with the base.

The workaround is to snap to the click event after all the rendering is done in the rendering method.

 this.$('> .node > .indent > a').click(this.toggleGrouped); 

You will also have to bind the toggleGrouped context in the initialize method, since it no longer binds automatically.

 initialize: function() { _.bindAll(this, 'toggleGrouped'); } 
+6
source

Found the answer. delegateEvents uses jQuery.delegate() , which for some reason does not accept selectors that start with a descender child:

http://api.jquery.com/delegate/#comment-66006048

+2
source

Another way to do this, I think, might be to simply take the child selectors > from the events hash and use event.stopPropagation() in the event handler as follows:

 toggleGrouped: function (evt) { evt.stopPropagation(); // event handling code } 

The first parent chain that listens for this event will receive it, and then it will not allow it to iterate over everything that could also catch the event.

+2
source

Source: https://habr.com/ru/post/1388620/


All Articles