Elfy
Elfy

Reputation: 1863

Remove specific event handler

Attaching event handler:

$(document).on('keypress', function(event){
  #1
});

This removes all keypress event handlers:

$(document).off('keypress');

I only want to remove #1 from my code above

Can this be done without using namespaces? I don't want to create random strings to be used as namespaces :(

Upvotes: 1

Views: 103

Answers (1)

six fingered man
six fingered man

Reputation: 2500

Pass the original handler to off. Make sure you're passing the original and not a new anonymous function that just looks the same.

This means you'll need to store it.

var handler = function(event){
  #1
};

$(document).on('keypress', handler);

$(document).off('keypress', handler);

Upvotes: 3

Related Questions