nb_nb_nb
nb_nb_nb

Reputation: 1381

Why is my function value being called twice?

I have a function that is being called in another function. It should return values of a json object. The json values change based on the filters I have set up.

Why are both values being called instead of just the last one.

My code:

$.getJSON(json, api_result => {

      myFunc('#api_results', api_result);
});

function myFunc(id, json_data) {
  $(id).click(function() {
    console.log(json_data);
  });
}

My result:

results

I have updated my filters to change parameters of my json but on click I get all my changes. Why can't I just get the last values of my filtered json?

Upvotes: 0

Views: 51

Answers (1)

Nick
Nick

Reputation: 147216

Every time you get a new set of data (from $.getJSON) you are calling myFunc and binding another handler to the click event on $(id). You need to remove any existing click event handlers before binding a new one:

function myFunc(id, json_data) {
  $(id).off('click').on('click', function() {
    console.log(json_data);
  });
}

Upvotes: 2

Related Questions