2

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:

  1. How do I fix my problem, so that myProcessedAttribute will contain the correct data instead of the data on first click?
  2. 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.

1
  • Can you post a demo on JSfiddle? Commented Oct 10, 2012 at 7:27

1 Answer 1

1

"create" event is called when dialog is created. Second time you open dialog, create event is not fired, because dialog object already exist on that element. If you want different values on same dialog widget, use "open" event. This is a sample

http://jsfiddle.net/RaWrC/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.