Search code examples
jqueryajaxbindunbind

jquery unbind and bind on ajax success


i am creating a slideshow, when i reach on end of lis and click right arrow, ajax should fire and load new list of images. When i reach the end of second list, ajax should fire agaiin. If i click twice fast ajax fires twice and changes global vars that i need, instead of only activating once. I can place hide after else to hide the button so that it can not be pressed twice until ajax success shows the button again. The button is just a div. I do not want to hide it because for a sec it is hidden, and i want it to be visible. If i try to unbind rightNav after else, i can not bind it back again on ajax success. What could be the problem?

rightNav.click( function(){
    if(index <= listLength - 2){
        index = index + 1;
        appendImage(index);
    }
    else {
        rightNav.unbind('click');
        nextUrl = '/GetPhotosCriterians?categoryid=' + pCategoryId + '&styleid=' + pStyleId + '&terms=' + pTerms + '&pos=' + nextPos;
        $.ajax({
            type: "GET",
            url: nextUrl,
            dataType:"json",
            success: function(data){
                imagesList = data;
                listLength = imagesList.length;
                appendImage(0);
                curentPos = nextPos;
                nextPos = nextPos + imgNumber;
                prevPos = curentPos - imgNumber;
                rightNav.bind('click');
            }
        });
    }
});

Solution

  • Your code doesn't work because rightNav.bind('click'); does not actually bind the click event to your function.

    The syntax for bind (in your case) is bind(event, callback).

    So you could either:

    a) Give a name to your function so you can assign it back, such as:

    var f = function() { if(index <= listLength - 2){ ...
    rightNav.click(f);
    

    And then you assign it back with:

    rightNav.bind('click', f);
    

    b) Ignore click when ajax is already loading:

    else {
            //rightNav.unbind('click');
    
            if (rightNav.loading) {
                return;
            }
    
            rightNav.loading = true;
            ...
            success: function(data){
                rightNav.loading = false;
            ...