D
D
dmitriyivvvv2018-04-29 16:25:35
JavaScript
dmitriyivvvv, 2018-04-29 16:25:35

Anonymous functions and removeEventListener?

Good afternoon!
There is this code :

function text(a) {
  alert(a);
}

Let's say I need to pass parameters to a function that will handle the event, for this I use the anonymous wrapper function.
The code:
el.addEventListener('click',  function() {
  text('it\'s finnaly working!');
});

The question arises, how can I then remove the event listener from this element, if the two anonymous functions are different functions and such an entry will not work:
Code :
el.removeEventListener('click',  function() {
  text('it\'s finnaly working!');
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2018-04-29
@dmitriyivvvv

It's simple: don't use anonymous functions.

var f1 = function() {
  text('it\'s finnaly working!');
};

el.addEventListener('click',  f1);
// ... 
el.removeEventListener('click',  f1);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question