最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

event listener - How to reuse EventListener if it already exists? [plain JavaScript] - Stack Overflow

programmeradmin1浏览0评论

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: /

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

Second use of #1 EventListener

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

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.

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/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

Second use of #1 EventListener

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

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.

Share Improve this question edited Jan 26, 2016 at 13:07 ScriptyChris asked Jan 26, 2016 at 12:47 ScriptyChrisScriptyChris 6694 gold badges17 silver badges50 bronze badges 4
  • Its a bit confusing. Also add code how you are assigning eventlistener – Rajesh Commented Jan 26, 2016 at 12:50
  • Look up how you remove event listeners. Just as you can add event listeners you can remove them from DOM elements as well. So it seems to me that you need to manage when an event listener added to an element and when not. – Glubus Commented Jan 26, 2016 at 12:52
  • If you're adding two listeners to the same element, then that's the problem. You should use N functions for the same event on the same element rather than N listeners to the same event. – Skaparate Commented Jan 26, 2016 at 12:54
  • I added code and JSFiddle demo – ScriptyChris Commented Jan 26, 2016 at 13:08
Add a ment  | 

3 Answers 3

Reset to default 3

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);
     }
 }());

I would use a counter approach if you must add event listeners inside another event. The event will not be added unless the counter for the event equals zero.

Live Preview: http://codepen.io/larryjoelane/pen/YwaYWM

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

//counters for each elements event
var aCount = 0, bCount = 0;

 (function()
 {
          function parent()
         {

       //if the counter equals 0
       if(aCount === 0){//begin if then

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

                  kid();
                }, false);

         //increment the counter
       aCount++;

       }//end if then


         };
         parent();

         function kid()
         {

       //if the counter equals 0
       if(bCount === 0){//begin if then

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

              }, false);

         //increment the counter
         bCount++;

       }//end if then

         } 
 }())

;

There are at least two general approaches:

  1. HTMLElement.onchange - you can replace event listener every time you are calling kid function. It's not a good solution in a general way, because there could be other modules which could add their onchange event listeners. But if it's OK with you system, this will work.

  2. You could add some state behavior. That is you just set some isInitialized variable to true in the first call of parent and kid functions, and then you check it in the next time. If it's false, then add an event listener.

发布评论

评论列表(0)

  1. 暂无评论