rgx71
rgx71

Reputation: 867

Callback function is executed right away

I have a confirm popup that ask for yes or no, this is the code:

Confirm({
    Title: 'Warning',
    Message: 'Are you sure?',
    Buttons: [{
        text: 'Yes',
        callback: function(){
            RRSubmitRemoveReportRequest($(this));
        },
        highlighted: true
    }, {
        text: 'No)',
        callback: null,
        type: 'no'
    }]
});

If if send the parameter $(this), I should use an anonymous function, otherwise it calls the function right away, anybody can explain me this please? Thanks

Upvotes: 0

Views: 242

Answers (2)

gdoron
gdoron

Reputation: 150263

It's easy to understand with an example:

function foo(i){
    return i*10;
}

var x = foo(1); // execute foo with 1 parameter;

var x = function(){ // creates a callback to the foo function.
    foo(1);
};

var x = foo; // pointer to foo function and then:
x(1);

Bottom line, a callback should be a function that will be invoked somewhere in the future, not a value of a function.

Upvotes: 4

gen_Eric
gen_Eric

Reputation: 227270

The callback property needs to be set to a function.

If you do:

callback: RRSubmitRemoveReportRequest($(this))

you are setting callback to the return value of the RRSubmitRemoveReportRequest function.

You need to pass it a function. RRSubmitRemoveReportRequest is a function, RRSubmitRemoveReportRequest($(this)) is a function call, so it's ran and its return value is used.

When you do:

callback: function(){
    RRSubmitRemoveReportRequest($(this));
}

you are passing a function, that when called, will call RRSubmitRemoveReportRequest correctly.

Upvotes: 2

Related Questions