0
for (key in this.mybutton)
       button = this.mybutton[key]

       $(button).click(function() {
            console.log("click:" + button)
       });

The result is always the name of the last button. How can I add multiple listeners in jQuery/javascript or erase the javascript reference button to a string in the for.

thanks in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Thomas
  • 1,008
  • 3
  • 16
  • 34
  • Using 'this' or maybe you need a cosure there. Could you provide a working sample as jsfiddle which show what are you looking for? – A. Wolff Jul 23 '13 at 10:20

1 Answers1

2

You need a closure new scope :

for (key in this.mybutton)
   (function(button) {
       $(button).click(function() {
            console.log("click:" + button)
       });
   })(this.mybutton[key]);
}

or just use this:

$(button).click(function() {
    console.log("click:" + this)
});

Concatenating a DOM element and a string in the console log doesn't seem like a very good idea ?

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • No, not a closure (the event handler *is already* a closure). You need to create a new *scope*. [See my comments here](http://stackoverflow.com/questions/17517111/javascript-binding-click-handller-inside-a-loop/17517127#comment25470265_17517127) for a more extensive explanation (this is just regarding the first snippet, of course the second one is a much better solution anyway). – Felix Kling Jul 23 '13 at 10:31
  • @FelixKling - thanks, that's a good explanation, and even if I understood why it worked, I've never really thought about the fact that any function will create a closure, and as such the closure isn't the reason it works, passing the parameter to keep it constant within the __new scope__ is! – adeneo Jul 23 '13 at 11:07
  • thanks,exactly what i want. The concatenation was just to give an simple example of my problem, it's doesn't have a real utility :p – Thomas Jul 23 '13 at 12:34