The server sends some JSON. It contains a list of structured data. I display this data as a list of textboxes, each of which has its own onClick event. On click, the value of the textbox is set to whatever is in the structured data (which is an unique ID, which means that each textbox should display the ID on click).
When I first click on any textbox, its value is set correctly -- with the ID from the data from the server. But as I click on other textboxes, they display IDs from the first-click textbox!
I've tried both closure var and $.proxy(), but they doesn't seem to work. I've checked the contents of myAttribute and they change on each iteration of the $.each() function. The click() event, however, seems to be evaluated at "runtime" and doesn't update.
The questions are:
- How do I fix my problem, so that
myProcessedAttributewill contain the correct data instead of the data on first click? - I feel my approach of having four nested functions might not be best practice.. Or is it?
Code:
$.ajax({
[...]
success: function (data) {
[...]
$.each(data.listOfData, function () {
[...]
var myAttribute = this.myCoolAttribute; // <-- closure
jQuery('<p/>')
[...]
.click(function () {
var myProcessedAttribute = process(myAttribute);
[jquery ui dialog...]
create: function () {
// it always contains the same data
// the data on first click, after that, it never changes.
$("#myDialog").html(myProcessedAttribute);
}
});
});
}
});
EDIT: I've just put alert(myProcessedAttribute) in click() and create events. In the former event, the alert displayed correct data. In latter event, the alert was displayed only on first click, but it never appeared again on subsequent clicks!
MY SOLUTION: I thought that on calling .dialog({...}) the new dialog replaces the old one, but I was wrong. I've solved the problem by destroying the old dialog before creating a new one.
BETTER SOLUTION: See answer below.