Igor Almeida
Igor Almeida

Reputation: 224

How can I overwrite a function in addEventListener?

In my application, there are several buttons which trigger my function loadObj(a). This function mainly loads the corresponding 3D object using the Three.js library.

When I choose a object and click the corresponding button, a set of three extra buttons appear which allow me to load three variations of the selected object. The code below already works for this scenario using addEventListener.

My problem arises when I select a different object, which triggers the code below again. Then, if I click one of the extra buttons for the newly selected object, it loads the correct object, but it also loads the previous one. If I choose a third object, if I click one of the extra buttons, it will not load just the corresponding object, but the previous two as well.

I have read that addEventListener works in a cumulative manner, where the functions just keep being added up. So, everytime it runs the loop below, it adds a new loadObj with the path of the new model to any other previous loadObj.

Is there any way to overwrite a function inside addEventListener? I need the previous loadObj to be removed from addEventListener before adding the new one.

    //Solve the scope/closure problem to able to call loadDress inside the "for" loop below
    function delegate(a) {
       return function(){
          loadObj(a)
       }
    }

    for(var item in paths){
       document.getElementById("size" + item).style.display = "inline-block";
       document.getElementById("size" + item).addEventListener("click", delegate(paths[item]), false);
    }

Upvotes: 0

Views: 486

Answers (1)

shadymoses
shadymoses

Reputation: 3443

If you run that loop every time you click the button, it's adding an event listener on every run. That's why you keep getting more and more items each time--you keep adding more functions.

Instead of trying to dynamically add new event listeners on dynamically added buttons, you can delegate your event listening to a parent element that is a direct ancestor of all of the buttons. Then you have a single event listener that works for all of your buttons without any extra effort. You just check to make sure a click is from the right type of element and then you can get any relevant information directly from that element (via data- or other attributes on the event object target).

Upvotes: 1

Related Questions