Swen
Swen

Reputation: 787

Function passed as parameter in other function is being fired multiplicatively

I have a function that creates a modal window with a "Confirm" and "Cancel" button. The function requires an action parameter, through which another function is called. In the example, this action is the unsubscribe AJAX call.

Only after "Confirm" is clicked, the AJAX call is made.

Here's when weird things happen. After the first time, each and every time I click the "Confirm" button again, it fires the action another time. So the first time it fires the action just once, the second time it fires it twice, the third time it fires it thrice. Etc.

I've been scratching my head over this for a while. It almost seems as if the action parameter keeps it's functionality, and every newly inputted action is added on top of that.

$.createActionModal = function( params, action ) {      
    if ( typeof params.title === 'undefined' ) { params.title= ''; }

    var actionModal = $( '#action-modal' );

    actionModal.find( '.modal-title' ).html( params.title );

    actionModal.show();

    actionModal.on( 'click', '.confirm-button', function( e ) {
        e.preventDefault();

        // Fire the action if "Confirm" is clicked
        action();

        actionModal.hide();

        return true;
    } );

    actionModal.on( 'click', '.cancel-button', function( e ) {
        e.preventDefault(); 

        actionModal.hide();

        return false;
    } );
}

Then in another file, I use this function to show a modal window with two options, Confirm and Cancel.

$(document).on( 'click', '.unsubscribe-button', function( e ) {
    e.preventDefault();

    var thisButton = $(this);

    var data = {
        'action': 'unsubscribe',
        'author_id': parseInt( thisButton.attr( 'data-author-id' ) ),
    };

    // Modal function is called here, the action paramater is a function wrapping the AJAX function
    $.createActionModal(
        {
            'title':    'Are you sure you want to unsubscribe?'
        },
        function() {
            subscription_ajax( thisButton, data );
        }
    );

});

And finally, the AJAX call that's being passed as the action.

var subscription_ajax = function( thisButton, data ) {
    $.ajax({
        url: ajax_url,
        type: 'POST',
        data: data,
        success: function( response ) {     

            console.log( 'Testing' );

            // ... Does ajax stuff

        }
    });
}

Upvotes: 0

Views: 39

Answers (1)

mbojko
mbojko

Reputation: 14669

Looks like with every click on $('.unsubscribe-button'), $.createActionModal() is called again, attaching new event listeners to its buttons (while the old ones are still there).

Create modal and attach listeners once, and on button click only show it.

Upvotes: 1

Related Questions