panthro
panthro

Reputation: 24061

Using on/off event bindings?

Im trying to unbind an event.

My event is:

 $(window).on('drop', this.onFileSelect.bind(this));

Later I:

$(window).off('drop', this.onFileSelect.bind(this));

But I can still drop.

Where am I going wrong?

Upvotes: 2

Views: 87

Answers (2)

haim770
haim770

Reputation: 49095

The recommended way to identify event listeners in jQuery (typically for later removal) is to use event namespacing, and in your case:

$(window).on('drop.onfileselect', this.onFileSelect.bind(this));

Then:

$(window).off('drop.onfileselect');

Note that onfileselect is an arbitrary identifier I chose, you can provide your own (plugin) name.

Upvotes: 1

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33870

Your problem here is that bind() return a new function. So the function you're trying to unbind is not the same of the function you are binding. jQuery then fail to properly unbind the event.

Save the reference of your function and use that reference:

var myFn = this.onFileSelect.bind(this);
$(window).on('drop', myFn);
$(window).off('drop', myFn);

Be sure that the variable is accessible by both scope.


That solution explain the problem. To solve your issue, you could A) do what I said in comment : $(window).off('drop'). B) Use namespace like haim770's answer. C) Use this answer (which is the worst solution IMO).

Upvotes: 1

Related Questions