ajaxStop inside a Click event in jQuery
I have the following code which displays a confirmation div when a link is clicked. The first time I run it this works, when the ajax request is finished the deleteConfirmation div slides up. But when I try it a second time (without开发者_StackOverflow社区 a refresh) the confirmation div slides up every time it's slid down, even when this click isn't triggered.
$("#deleteConfirm").click(function() {
if(debug)
console.log("deleting "+$("#deleteConfirmationCampaign").html());
$("#mappingsRemove").html("Deleting Campaign and Mappings...");
// remove each mapping underneath the campaign
deleteCampaign(apiUrl, "mappings", account+"/"+campaignToDelete[1], "confirmDelete");
$(document).ajaxStop(function() {
$("#mappingsRemove").html("Finished");
// slide up the delete confirmation dialog
$("#deleteConfirmation").slideUp();
});
});
I have several requests that occur in my deleteCampaign function, am I using this incorrectly?
I think whats happening is the first time this triggers it sets a global listener for ajaxStop. And of course this triggers like all of the time, so it always tries to slideUp the confirmation div. Perhaps I need to stop the document listener to ajaxStop after it's slid up for the first time?
Any advice would help thank you!
You're right about what happens. But i'm not sure that ajaxStop is the best event to listen to. It fires when all requests have finished, right?
I think you would want react only on the requests that are related to your deleteCampain function.
You could use deferreds to execute a function when all the significant request have returned.
var ajax1 = $.ajax("/deleteCampain.php"),
ajax2 = $.ajax("/deleteCampain2.php");
$.when(ajax1, ajax2).then(function(){
$("#mappingsRemove").html("Finished");
$("#deleteConfirmation").slideUp();
});
See:
http://api.jquery.com/category/deferred-object/
http://api.jquery.com/jQuery.when
You might set a global boolean so it only runs one time:
$(document).ajaxStop(function() {
if (!window.firstStop) {
$("#mappingsRemove").html("Finished");
// slide up the delete confirmation dialog
$("#deleteConfirmation").slideUp();
window.firstStop = true;
}
});
I unbinded the document and the ajaxStop function after the initial round of requests are finished,
Please let me know if this is going to cause any issues:
// listen for the ajax requests to finish
$(document).ajaxStop(function() {
// set the mappings remove to say finished
$("#mappingsRemove").html("Finished");
// slide up the delete confirmation dialog
$("#deleteConfirmation").slideUp();
// unbind the listener
$(document).unbind('ajaxStop');
});
精彩评论