ajax - jQuery - Off() not working depending of the event -


i'm using "off event" avoid multiple ajax requests (if user multiple clicks, example). works perfectly.

the problem is, depending on how "on('click')" event called, event off() doesn't work. give example:

function:

var addcomment(elem) = function(){     $.ajax({         type: "post",         url: '../../ajax/request.php',         datatype: 'json',         data: data,         beforesend: function(){            // after line, click elem doesn't            elem.off('click');         },         success: function(result){             if (result.success){                console.log('success!');             }else{                console.log('no success...');             }             //making "elem" clickable again             elem.on('click',function(){                 addcomment(elem);             });         },         error: function(xhr, ajaxoptions, thrownerror){             alert("error status: " + xhr.status + " thrown errors: "+thrownerror);         }     }); } 

events:

// using this, off event works $('.divarea button.newcomment').on('click',function(){     addcomment($(this)); });  // using this, off event not executed $('.divarea')     .on('click', 'button.newcomment',function(){         addcomment($(this));     }) 

why in second case, off() doesn't work , should off() works in both event calling examples?

thanks in advanced.

the reason second version doesn't work because when use delegation, event binding not on button, it's on .divarea. delegation works having handler automatically check whether target of event matches selector delegated -- that's how it's able extend elements didn't exist @ time binding established.

since there no bindings on individual elements, can't remove them .off.

what can delegate selector class, , change class when handle event.

$('.divarea').on('click', 'button.newcomment:not(.handled)', function() {     addcomment($(this)); });  function addcomment(elem) {     $.ajax({         type: "post",         url: '../../ajax/request.php',         datatype: 'json',         data: data,         beforesend: function(){            // after line, click elem doesn't            elem.addclass("handled");         },         success: function(result){             if (result.success){                console.log('success!');             }else{                console.log('no success...');             }             //making "elem" clickable again             elem.removeclass("handled");         },         error: function(xhr, ajaxoptions, thrownerror){             alert("error status: " + xhr.status + " thrown errors: "+thrownerror);         }     }); } 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -