Cor Basson
Cor Basson

Reputation: 43

$.getJSON Callback Help - Not a Function

My context is as follows:

I have a variable 'qq' - I want to assign data to this variable from an API call, and once the data has been assigned, I then use this data in a paint/binding process.

The API call and assigning to var 'qq' works fine - but I cant seem to get my callback to work - I keep getting an error: callback() is not a function

This is what my code currently looks like:

var qq = [];

// binding function - to be run after data loader has completed
function sayIamDone() {
    alert('I Am Done');
    // do data bindings with qq
}

// load data from api into var qq

function dataLoader(inp,callback) {
    let url = 'http://localhost:65232/api/layercolor/' + inp;
    console.log(url);
    $.getJSON(url,function(result) {
        qq = eval('({' + result + '})');    
        //console.log(qq);
        callback();
    });
                
}

// call data loader
dataLoader('Prov', sayIamDone());

From the above I get the following error in my chrome console:

Uncaught TypeError: callback is not a function

I have tried the following - which seems to work:

dataLoader('Prov', function () { alert('I Am Done');});

but it is not ideal in my context, as I want to call dataLoader('Prov',XXX()) where XXX() could be a number of different functions using the newly loaded values in qq

Any suggestions as to where I am missing the boat please?

Upvotes: 0

Views: 227

Answers (2)

xianshenglu
xianshenglu

Reputation: 5369

change:

dataLoader('Prov', sayIamDone());

to

dataLoader('Prov', sayIamDone);

because:

sayIamDone is function ,sayIamDone() is the result of function.Normally, sayIamDone() is undefined or return value in the sayIamDone;

want to use arguments?you can do this:

dataLoader('Prov', callFunc(n));

function callFunc(arg) {
    return function() {
        sayIamDone(arg);
    };
}

or more arguments?you can do this by spread

dataLoader('Prov', callFunc(n));

function callFunc(...arg) {
    return function() {
        sayIamDone.apply(null, arg);
    };
}

Upvotes: 1

Mario Cianciolo
Mario Cianciolo

Reputation: 1261

By running dataLoader('Prov', sayIamDone()); you are passing to dataLoader the result of sayIamDone function. You have to pass it without parenthesis in order to pass the function itself.

dataLoader('Prov', sayIamDone);

Upvotes: 1

Related Questions