pass a function as a parameter and then execute it in a jquery function

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.

Answers:

Answer

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);
Answer

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/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.