Unbind Backbone View Events

2019-01-23 16:38发布

问题:

I have the falling events hash -

events:
  'click #someButton : 'someFunction'

To close the view I have tried

close:
  $("#someButton").unbind("click")

and

   `close:

       $("#someButton").remove()`

But someFunction is still being fired more than once. How do I unbind this event from the button?

I've also tried

$(@el).find("#someButton").unbind("click") as well 

回答1:

Backbone.js view events are delegated to the view's el (so there is no event bound to your #someButton element but rather when a click event bubbles up to the el it checks to see if the event came from an element matching that selector), that being the case to remove the event you need to remove it from the el, for example

  $(this.el).off('click', '#someButton');

If you want to remove all delegated events you can just use the view's undelegate method



回答2:

Jack's explanation and answer are great. Unfortunately, his code example didn't work for me. Instead of using:

 $(this.el).off('click', '#someButton');

I had to use:

 this.$el.off('click', '#someButton');

which makes sense to me, because the event was bound to this.$el object.



回答3:

To add further, I used this.$el.off(); inside an initialize within a subview to destroy all events tied to the subview. The same event would fire X number of times a data refresh was called.

I saw the duplicated targets using:

var $target = $(e.currentTarget);
console.log($target);

I would add a comment to an answer, but I have low reputation.