0

I have a for loop which is supposed to assign functions based on user input (binding the function to a button). Instead, no matter which button is clicked (except the cancel button) the same function runs.

The function looks like this...

Per the requests below, here's a cleaner example :

HTML

<button id="myButton">
 Button 1
</button>
<button id="myButton2">
  Button 2
</button>
<button id="myButton3">
  Button 3
</button>

JAVASCRIPT

 var myFunctions = {
            myButton: function(o){ alert("Button 1 pressed! (" + o +")"); },
        myButton2: function(o){ alert("Button 2 pressed! (" + o +")"); },
        myButton3: function(o){ alert("Button 3 pressed! (" + o +")"); }
    }
    function runBinds(binds){
          for(bind in binds){
                var myButton = document.getElementById(bind),
                    myCall = function(){
                        binds[bind]("Appended info");
                };
            myButton.addEventListener('click',myCall,false);
        }
    }

    runBinds(myFunctions);

Jsfiddle

With closures

Without closures

As I mentioned before, I tried using closures and this did not resolve my issue, so it is not a duplicate.

Ethan
  • 787
  • 1
  • 8
  • 28
  • There is a lot going on here, some of which is based on DOM selectors when you're not showing any HTML. Instead break the code down to a minimal example that reproduces the problem. – dmeglio Sep 16 '16 at 23:45
  • Please update your answer this is a mess. just show your html and eventlistener function – user3791775 Sep 16 '16 at 23:46
  • I have updated the question with simplified code. – Ethan Sep 16 '16 at 23:58
  • @Ethan, what's happening is that the button is clicked, `myCall()` is called, and then `binds[bind]()` is executed. The `myCall` function is a closure around the `bind` variable. After the loop finishes, the value of `bind` is "myButton3". What you want to do is pass the value of `bind` instead like : https://jsfiddle.net/ug19xsmy/4/ – mowwwalker Sep 17 '16 at 00:07
  • Wow, that's exactly what I was looking for. Thank you! Want to post as an answer so I can mark it correct? – Ethan Sep 17 '16 at 00:10
  • This seems to work: for(let bind in binds){.... (note the 'let') – user3791775 Sep 17 '16 at 00:12
  • Interesting... Unfortunately neither are actually working in my larger project... Guess I'll just have to figure it out. Between the let trick and the answer @mowwwalker gave, should be good.... – Ethan Sep 17 '16 at 00:15

0 Answers0