chickpeas
chickpeas

Reputation: 443

bind and unbind function with a name

I need to bind and unbind a function on click. The problem is that I need the click event (also 'this' as the clicked element would be fine)

  function clickElement(e) {
  [...]
   //here I need event or this clicked element
  }

this would works, but doesn't have the event parameter

$('.clickme').on('click', clickElement)

this would works but I can't unbind the specific function

 $('.clickme').on('click', function(e){clickElement(e)})

this doesn't work:

 $('.clickme').on('click', clickElement(e))

why?

I need to use .on instead of .click because later I need to unbind clickElement and only clickElement like this:

  $('.clickme').off('click', clickElement);

Upvotes: 0

Views: 85

Answers (1)

epascarello
epascarello

Reputation: 207501

The first choice is exactly what you need

 function clickElement(e) {
      console.log(e, this);      
  }

  $('.clickme').on('click', clickElement);

The reason why

$('.clickme').on('click', function(e){clickElement(e)})
$('.clickme').off('click', function(e){clickElement(e)})

does not work is because it is a new anonymous function and it will not map to the one you used in on(). If you need to do that, you would have to keep a reference to that.

var myFunc = function(e){clickElement(e); };
$('.clickme').on('click', myFunc ).data("fnc", myFunc);

and to remove it

var elem = $('.clickme');
elem.off('click', elem.data("fnc") );

Upvotes: 1

Related Questions