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.