简体   繁体   中英

Unbind Backbone View Events

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 

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM