1

I have a form that I'd like to prompt the user to save changes for if there are changes. I'm trying to use the jQuery UI dialog box with the jQuery deferred object but am seeing some weird behavior. Here's what I'm doing:

function clickEventHandler()
{
  if (checkForChanges())
  {
    $.when(dialogChanges()).then(clickEventHandler());
    return;
  }
};
function dialogChanges()
{
  var def;

  def = $.Deferred();
  $("#tmplUnsavedChanges").tmpl().appendTo("body");
    this.__dialog = $("#divUnsavedChanges").dialog({
      resizable: false,
      modal: true,
      buttons: {
      Continue: Function.createDelegate(this, function ()
      {
        this.__origTemplate = this.__newTemplate;
        this.__dialog.dialog("close");
        def.resolve();
      }),
      Cancel: Function.createDelegate(this, function ()
      {
        this.__dialog.dialog("close");
        def.reject();
      })
    }
  });

  return def.promise();  
}

So I call a function when I click a link. It checks if there are changes, if so it launches the dialog that returns the deferred promise. But what I've found is that it always calls the done function right away getting into a race condition. However, if I instead call it this way, it works. $.when(dialogChanges()).then(function() { clickEventHandler()}); Why would that be? I've also tried wrapping the call within then() with Function.createDelegate but that doesn't work either.

When I read the instructions on done here, it appears to take functions instead of creating the function within the parameter itself.

Anyway, I'm fine with leaving it as is since it works but just wanted to understand so I don't make mistakes down the road.

Thanks.

4

1 回答 1

3

您的代码几乎是正确的。您需要从以下位置删除额外的一对大括号:

.then(clickEventHandler())

因为目前您正在立即调用该函数,并将其结果传递给.then,而不是注册 clickEventHandler.then回调,即:

.then(clickEventHandler)
于 2013-05-23T19:39:31.503 回答