Sumit Surana
Sumit Surana

Reputation: 1584

Jquery off not removing event handler in Ember application

I am not able to remove a event handler from the ember application by using off.

my handler function is

setClickEvent: function(){
  var panel = this.$();
  if(panel && panel.find(event.target).length === 0 && this.get('isOpen')){
    this.send('cancel');
  }
}

and I am calling this function in didInsertElement function using the below code

didInsertElement: function(){
  Ember.$('body').on('click', Ember.run.bind(this, this.setClickEvent));
}

and calling the off in willDestroyElement function as below

willDestroyElement: function(){
  Ember.$('body').off('click', this.setClickEvent);
  this._super();
}

I tried to go through many stackoverflow questions related to it. Which suggested to place an empty on after the off, I tried it but it didn't work.

The problem is that whenever I am moving away from the page and coming back I am finding two handlers handling the same event, because the previous event handler has not got removed and the event handlers are getting stacked up.

Upvotes: 2

Views: 329

Answers (1)

spectras
spectras

Reputation: 13542

That's unrelated to ember actually. The issue is this part:

Ember.run.bind(this, this.setClickEvent)

What it does is bind creates a new function bound to this. Then that new function is attached as a handler. However, you try to off() the original setClickEvent instead of the new function.

Try to bind the function when the object is created and store it for later use:

init: function () {
  this._super();
  this._setClickEvent = Ember.run.bind(this, this.setClickEvent);
}

Then in your didInsertElement and willDestroyElement, use the bound function directly, this._setClickEvent.

The point being off must be given the exact function that was given to on, otherwise it will not find it in its watcher list and will not remove it.

Upvotes: 4

Related Questions