Search code examples
javascriptevent-listenerreusability

How to reuse EventListener if it already exists? [plain JavaScript]


I have function A with addEventListener #1 on HTML element. It does some work and executing some functions. Further in code there is other B function with addEventListener #2, which does some other work. Both EventListeners are at change "mode".

It works but i noticed that when i execute function A, it properly works and it executes again B function with it's addEventListener #2. So then i have got two (or more - depends on how many times I use #1 listener) #2 EventListeners (in B function).

JavaScriptCode (simplified):

var a = document.getElementById('firstSelect'),
    b = document.getElementById('secondSelect');

 (function()
 {
          function parent()
         {
                a.addEventListener('change', function(ev)
                {
                    alert(ev.target.innerHTML);

                  kid();
                }, false);
         };
         parent();

         function kid()
         {
                b.addEventListener('change', function(ev)
              {             
                alert(ev.target.innerHTML);

              }, false);

         } 
 }());

JSFIDDLE: https://jsfiddle.net/Chriss92/u4yrypug/

In Chrome it looks like this - when click (use) #1 EventListener more than once, it's adding one #2 EventListener, so then when I use #2 it executes it's code many times (as it's created or added many times) :

First use of #1 EventListener

enter image description here

Second use of #1 EventListener

enter image description here

... and when i click five times on #1 EventListener it adds five #2 EventListeners:

enter image description here

And so on, more times i click on #1 EventListener, more #2 EventListener is added.


My QUESTION is: how to REUSE EventListener instead of adding it, when it's created already? I want clean JavaScript solution, not jQuery, please.


Solution

  • Try this

    var a = document.getElementById('firstSelect'),
    b = document.getElementById('secondSelect');
    
    (function()
     {
          function parent()
         {
                a.addEventListener('change', function(ev)
                {
                    alert(ev.target.innerHTML);
    
                  kid();
                }, false);
         };
         parent();
    
    
         function kid()
         {
            b.removeEventListener('change', kid_handler, false);
                b.addEventListener('change', kid_handler, false);
         } 
    
         function kid_handler(ev){
            alert(ev.target.innerHTML);
         }
     }());