Unbind Backbone View Events

2019-01-23 16:01发布

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 

3条回答
劳资没心,怎么记你
2楼-- · 2019-01-23 16:49

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.

查看更多
你好瞎i
3楼-- · 2019-01-23 16:52

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.

查看更多
一夜七次
4楼-- · 2019-01-23 16:56

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

查看更多
登录 后发表回答