jbolanos
jbolanos

Reputation: 625

Multiple instances of .click() in dynamic code

I have a complex set of dynamic functions that I'm having a problem with more than one instance of .click(). In the below code the first click (saveLocalChart) only calls itself once each time the editChartModal() is called but the removeLocalChart click calls for each time the function was called.

function editChartModal(location) {
    if(!localStorage.getItem(location)){
        $('.saveLocalChart').click(function(e){
            e.preventDefault();
            console.log('add chart: ', location); // DEBUG
            var kpiString = $('#'+location).data('params').kpistring;
            var rtt = $('#'+location).data('params').rtt;
            saveChartLocal(location,kpiString,chartTitle,chartSubTitle,rtt);
            $('.clearChart').show();
            $('.saveChart').hide();
        });
    }else{
        $('.removeLocalChart').on('click', function(e){
            e.preventDefault();
            console.log('remove chart: ', location); // DEBUG
            localStorage.removeItem(location);
            $('.clearChart').hide();
            $('.saveChart').show();
        });
    }
}

Console Snapshot:

Snapshot of console

Any ideas what could be causing this without having to upload my entire codebase (which has gotten bloated)?

Upvotes: 0

Views: 72

Answers (2)

A. Wolff
A. Wolff

Reputation: 74420

Each time you call editChartModal() function, you are binding new click handlers. Just unwrap it from this function.

Upvotes: 1

prothid
prothid

Reputation: 606

The best practice is to always unbind the click event before binding a new one. So just before .click(..., add .unbind('click') and before .on('click', ..., add .off('click') and see if you still have the same issue.

Upvotes: 1

Related Questions