7

I was wondering which is the way to make this simple (and maybe stupid) thing with jQuery.

I have a function like this:

function setSomething() { 
    make some stuff; 
}

and then another function like this:

generalFunction(par1, par2, par3) { 
    do other stuff; 
    execute function called in par3;    
}

Well, if I write something like this it doesn't work:

c=setSomething(); 
generalFunction(a, b, c);

So what's the way to call a function as a parameter of another function and then execute it inside?

I hope I was clear enough.

Any help will be appreciated.

Thank you in advance for your attention.

Willem D'Haeseleer
  • 19,661
  • 9
  • 66
  • 99
bobighorus
  • 1,152
  • 4
  • 17
  • 35

2 Answers2

15

leave out the parentheses , you can then call the parameter as a function inside your "generalFunction" function.

setSomething(){
   // do other stuff  
}

generalFunction(par1, par2, par3) { 
    // do stuff...

    // you can call the argument as if it where a function ( because it is !)
    par3();
}

generalFunction(a, b, setSomething);
Willem D'Haeseleer
  • 19,661
  • 9
  • 66
  • 99
  • 2
    +1. Noting that the same thing applies to the code in the question that uses `c`, that is you would say `c = setSomething; generalFunction(a,b,c);` (but of course as you've shown you don't _need_ `c` to make it work). – nnnnnn Apr 02 '12 at 10:44
  • Yeah! The parentheses! Clean and simple! :D Thank you for the help! You can vote for my question if you want. – bobighorus Apr 02 '12 at 10:51
0

Here is another example for those who want to pass a parameter to a function that is passed in as a call back:

$(document).ready(function() {
  main();
});

function main() {
  alert('This is the main function');
  firstCallBack(1, 2, 3, secondCallBack);
};

function firstCallBack(first, second, third, fourth) {
  alert('1st call back.');
  var dataToPass = first + ' | ' + second;
  fourth(dataToPass);
};

function secondCallBack(data) {
  alert('2nd call back - Here is the data: ' + data)
};

Here is the JSFiddle link: https://fiddle.jshell.net/8npxzycm/