FYI, you don't quite understand closures, because you don't have one in this case. :-)
Your for-loop (var i = 0; i < contacts.length; i++) { ... } doesn't create a closure - this just creates a block, which has no special scoping rules at all in JS. By the time the loop finishes, you have created three distinct closures (your event handlers, which are inner functions) - but they all point to the same variable i, which is 3. If you had said contacts.each(function(contact) { ... }), and then referred to contact.id inside the function, you would have had the results you were looking for because each iteration of the loop has its own closure. Does that make sense? -Fred On Mon, Jun 30, 2008 at 7:25 PM, greenie2600 <[EMAIL PROTECTED]> wrote: > > I understand closures. However, I haven't found an elegant way to > solve the problem. This won't work: > > function populateContactsList( contacts ) > > var theUL = document.getElementById("addr-book-index"); > var thisLI = null; > > for ( var i = 0; i < contacts.length; i++ ) { > thisLI = document.createElement("li"); > > thisLI.appendChild( document.createTextNode( contacts[i].name ) ); > theUL.appendChild( thisLI ); > Event.observe( thisLI, "click", function() { > openContact( contacts[i].id ); > } ); > } > > } > > ...because every call to openContact() will receive 3 as the parameter > - the value of contacts[i].id at the time the outer function exits. -- Science answers questions; philosophy questions answers. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Spinoffs" group. To post to this group, send email to rubyonrails-spinoffs@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/rubyonrails-spinoffs?hl=en -~----------~----~----~----~------~----~------~--~---