views:

39

answers:

2

Hello, my problem is that the parameter that gets bound to the function call wrapped by addEvent is always the last value set on the variable passed.

I have an example on mooshell here : http://mootools.net/shell/S2GxT

Can someone please explain why this doesn`t work (and maybe a workaround), as in server side languages this would be a very common case and expected to work.

Cheers! Haakon

A: 

Ok, I found some commented out code where I tried to solve this before by looking at an example on the net, that I didnt find this time. So its solved, and I`ve replicated it here : http://mootools.net/shell/CJ3R5/

I still have a hard time figuring out why this is necessary, so maybe someone can help me with that instead?

haalind
A: 
  1. When you bind an object to a function, any reference to "this" in the function will point to the object you bounded to the function.
  2. In the first code example, you bound "this". If we look at the state of things, "this" contains an "i" variable which value is 4 after the loop. Therefore, the bound function will know that "this.i" is 4.
  3. In the second code example, which is too complicated in my taste, you bound the current value of i, not the final value of i. Therefore alerting "i" yielded the current value as the function knew it at the moment of binding.
  4. I simplified the second code example, in order to show how it should work in my opinion. http://mootools.net/shell/Ty3dW/ Note that by binding "i", in the function "this" is "i".

remember that in general, in Javascript, "this" is the caller of the function. If you want to change that, bind "this" to the element you want. On a more general note, something that really opened my eyes is Doug Crockford's explanation about private members: http://javascript.crockford.com/private.html

Hope I helped. :)

Nir
Yes you did :)It`s not obvious to me that binding i will be this in the function, but I see that I took the long road and will use your method instead. I`ll also read up on the link, thanks a lot!
haalind
Great, I'm happy it helped.
Nir