Dynamic listeners based on array
<p>I'm playing with mobile app creation with jQuery and an api I built using Slim.</p>

<p>My overall goal is to create a list of buttons that when clicked will call a function with the appropriate parameters.</p>

<p>I am successfully sending my request to slim, getting a list of users and storing the results in a global array of User objects.  </p>

<p>Next I am iterating through the array appending html to the document to show the buttons.  At the same time I am adding a click listener.  The listener gets added, but not like I expect.</p>

<p>Users is an array of user objects with global scope.  A user object can be boiled down to [{"name":"User's name"}].</p>

<p>Also relevant might be the fact that I'm doing this in a call back.  </p>

<pre><code>$.getJSON(url, function(data){
    for(i=0;i&lt;data.length;i++)
    {
         var u = new User();
         u.name = data[i]['name'];
    }
})
//The success handler DOES get called.
.success(function() {
    for(var i=0; i&lt;users.length; i++)
    {
        //this part works.  users[i] is accessed as expected.
        var html_string = '&lt;li&gt;'+users[i].name+'&lt;/li&gt;';

        $("#myUL").append(html_string);
        $("#myUL li:last").click(function(){
            //logs undefined
            console.log(users[i].name);

            //Handle the event
            eventHandleFunction()
        });
    }
})
</code></pre>

<p>I'm well enough versed in programming in general to know that what I'm doing does not fall into best practices, but I am so illiterate in javascript that I don't know the right way to fix it.  In addition to the howto answer I'd really appreciate anyone who took some time to point me to useful resources.</p>

<p>Update: After reading an answer about using delegate to assign handlers I have updated my code a bit.  Now it looks like this.  Note: I've only not updated the code above in order to get an answer to the 'why' part of the original question.</p>

<pre><code>$("#myUL").delegate("li","click",function(){
            //sets the attribute name of the global var user
    user.name = $(this).text();
            //lets see what user.name is now.  Oh, look.  It's what i expect
    alert(user.name);
    //do whatever else i want to do here.
});

//This json request is now (i believe) entirely unnecessary to answer the question.
$.getJSON(url, function(data){
    for(i=0;i&lt;data.length;i++)
    {
         var u = new User();
         u.name = data[i]['name'];
    }
})
//The success handler DOES get called.
.success(function() {
   //No longer relevant
})
</code></pre>
