removeEventListener - Return False Not Stopping Listener

56 Views Asked by At

I'm listening for changes in two variables height and weight. When both evaluate to true I expected the return a value of false to stop the listener. It keeps appending <script type="text/javascript" src="js/modelers/average_aboveaverage.js"></script> when I move a range slider elsewhere in my code.

  function makeModeler() {
    document.addEventListener("change", function(){
      var height = document.getElementById('height-class').value; 
      var weight = document.getElementById('weight-class').value;
      shape = height + "_" + weight;
     
      if (!(height && weight)) { 
        return true;

      } else {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "js/modelers/"+shape+".js";

        document.body.appendChild(script);
        return false;        
      }
    });  
   
  }

  makeModeler();

  document.addEventListener("change", makeModeler);
  document.removeEventListener("change", makeModeler, false);
2

There are 2 best solutions below

1
On

You are adding the event infinitely in every change since you are doing:

document.addEventListener("change", makeModeler);

And the makeModeler function also adds at first that onChange event

0
On

I had to find an unconventional way to stop eventListener. eventTarget didn't work for me bc of the "dynamic" way I'm rendering data on my site. As a note, addEventListener should ship with an option to stop it from running infinitely. Seems obvious.

I added the listener to a do/while:

  var height = document.getElementById('height-class').value; 
  var weight = document.getElementById('weight-class').value;
  
  do {
    document.addEventListener("change", function(){
      
      var height = document.getElementById('height-class').value; 
      var weight = document.getElementById('weight-class').value;

      shape = height + "_" + weight;
     
      if (!(height && weight)) { 
        return true;      

      } else {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "js/modelers/"+shape+".js";

        document.body.appendChild(script);
        document.getElementById('weight-class').id = "weight-class2";
        
      }
      
    });  
  }
  while (height && weight);

I changed the id of the element to stop the while condition from evaluating to true. A more experienced programmer may know of a better to stop the condition.