0

I have a problem with callbacks. I'm using semantic and i want a callback to be fired to do something on response (onResponse).

I can make it this way and it works:

var drop = $('.ui.dropdown');
drop.dropdown();
drop.api({
    action: 'someAction',
    on: 'now',
    onResponse: funcion(response){
        //do some operations using the response variables AFTER the server    
    }
});

But i want to do it this other way:

var drop = $('.ui.dropdown');
drop.dropdown();
drop.api({
    action: 'someAction',
    on: 'now',
    onResponse: func(response)
});

function func(response) {
    //do some operations using the response variables AFTER the server responses
}

As you may have noticed, the second way is erroneous because the function is doing it's operations before the response variable get's fulfilled.

Is there a way to do this correctly?

Hernan
  • 1,149
  • 1
  • 11
  • 29
  • 1
    Not exactly a duplicate, but still the same reason: [Why is the method executed immediately when I use setTimeout?](http://stackoverflow.com/questions/7137401), `func(...)` will call the function `func`. Without the braces you pass/store store the function object itself for later usage. – t.niese Dec 04 '16 at 16:05

1 Answers1

4

You are calling function with this: func(response) you should use only func. So, please try:

drop.api({
    action: 'someAction',
    on: 'now',
    onResponse: func
});
mitch
  • 2,235
  • 3
  • 27
  • 46
  • 2
    Because when you don't pass argument the `func` is a pointer to that function. When you pass argument, you are executing this function right now. – mitch Dec 04 '16 at 16:11
  • 2
    @Hernan, because you do not call the function at that point, you just want to store your function in the `onResponse` property, so that the `drop.api` can later call that stored function, and at that point the argument will be passed by the code of `drop.api`. – t.niese Dec 04 '16 at 16:11