I have been struggling to find a good solution for this problem for a long time. (And I have GOOGLED IT many times). I'm trying to avoid the same function running multiple times when I recall it after an ajax call. I'll give a simple example using the following code:
I load a list of users from my db using php:
while(some loop){
$users.='
<div>
<div>user name</div>
<div class="replace">replace user</div>
<div class="delete">delete user</div>
</div>
';
}
And display them inside a div:
<div class="user_wrap">
<?php echo $users; ?>
<div id="add_user"></div>
</div>
Now on the front end I can delete or replace each user or add a new user to the div so I run all three functions on document ready:
$(document).ready(function(){
addUser();
deleteUser();
replaceUser();
});
function addUser(){
$("#add_user").on("click",function(){
//first load a list of users then select one from it
$.post("url",{},function(response){
//add new user to the user wrap
deleteUser();
replaceUser();
});
});
}
function deleteUser(){
$(".delete").on("click",function(){
$.post("url",{},function(response){
//delete user
});
});
}
function replaceUser(){
$(".replace").on("click",function(){
$.post("url",{},function(response){
//replace user with a different user
});
});
}
Now the problem comes when I add a new user using ajax I have to rerun both of the deleteUser and replaceUser functions. So thoes functions begin to pile up and can run multiple times in a row. In some cases this is harmless to the result of the function but in some cases it actually harms the result of the function and in adition doesnt it take a lot of system resourses? The only way I was able to prevent it was using Triggers by setting up a global variable and doing some thing like:
DelteUserTrigger = 0;
function deleteUser(){
if(DelteUserTrigger==1){return false;}
else{
DelteUserTrigger=1;
$(".delete").on("click",function(){
$.post("url",{},function(response){
DelteUserTrigger==0;
//delete user
});
});
}
}
But this mehtod doesnt work as expected it gets the function "stuck" many times as if the trigger didnt change, the on click event just stops responding.
I have also read something about function closure in JS to prevent the same function from running multiple times but I didnt quit understand how to implement that with the ajax call. And is it really useful in this case or am I doing everything wrong here? I would really appreciate some help here.
Just use event delegation, and you'll only have to set up the event handlers once (when the page loads):
function deleteUser(){
$(document).on("click", ".delete", function(){
$.post("url",{},function(response){
//delete user
});
});
}
Once that's been called, then it'll work for all the user stanzas whether they were there when the page loaded or not. You don't need to do anything after the ajax completes.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments