I currently have code similar to this for a form:
$('#some-form')
.submit(function()
{
// Make sure we are not already busy
if($(this).data('busy'))
return false;
$(this).data('busy', true);
// Do post
$.post("some/url", $(this).serialize(), function(data)
{
if(data.success) // Success is a boolean I set in the result on the server
{
// Deal with data
}
else
{
// Display error
}
$('#some-form')
.removeData('busy');
});
return false;
});
My issue is that I would like to somehow remove the need for knowing the form id in the post callback. In the end where I remove the busy data from the form, I’d like to somehow not have that hard coded. Is there any way I can do this? Is there a way I can hand whatever is in this to the post callback function? Since I know the id right now, I can get around it by doing what I have done, but I’d like to know how to not be dependent on knowing the id, since often I don’t have an id. (For example if I have a link in each row in a table and all the rows have the same click handler.
Set a variable with the value “this” before creating the callback.
Then use that variable name in the callback function.
That way, the variable with the form will be available inside the callback.
When you declare a function, that function will have access to all the variables in that same scope, even if it’s called after the function it was declared in has returned.
You can read about closures in detail at: http://www.jibbering.com/faq/notes/closures/