Leron
Leron

Reputation: 9876

How to set function as value to property that expects anonymous function

I'm using jquery API - jquery DataTables and I have this code snippet :

oSettings.aoDrawCallback.push({
    "fn": function(){

    },
    "sName": "user"
});

Inside the body of the function I want to execute an Ajax request. when I write it drectly here like so:

"fn": function(){
 $.ajax({
    url: "url",
    type: "POST",
    async: false,
    data: data,
    success: function (data) {
        console.log(data);
    }
    }),

There is more that is just an example to show the way everything's work fine. Then I create my own function :

function initCredits(id, inputVal, chkSelected) {

console.log(id);
$.ajax({
    url: "URL",
    type: "POST",
    async: false,
    data: data
    success: function (data) {
    }
 })
 }

and try to assing it do fn like so:

oSettings.aoDrawCallback.push({
    "fn": initCredits(id, inputVal, chkSelected),
    "sName": "user"
});

which gives me an error Uncaught TypeError: Cannot read property 'apply' of undefined. Now the text comes from the jquery DataTables API but there may be only two reasons I can think of that may break my code, since it's working befor taking it to outer function. First - I'm tryng to assing the function in a wrong way and second - as you may see I need three variables for my ajax request (id, inputVal, chkSelected) which are collected from the function where I'm doing this :

oSettings.aoDrawCallback.push({
    "fn": initCredits(id, inputVal, chkSelected),

but the console log shows that the values are correct so I think this is less likely to be the problem, but still I consider it.

Upvotes: 0

Views: 108

Answers (1)

Quentin
Quentin

Reputation: 944193

This:

"fn": initCredits(id, inputVal, chkSelected),

calls the function and assigns the return value.

To assign the function, just do:

"fn": initCredits,

Upvotes: 1

Related Questions