7

I would like to pass to a jQuery function a regular function, instead of the usual anonymous function, but I'm not sure how such a thing could be done.

Instead of this:

function setVersion(feature) {
      $.post("some.php", { abc:"abc" },
      function(data){
         // do something here
      }, "json");
}

I would like to do this:

function foo(data){
   // do something here
}

function setVersion(feature) {
      $.post("some.php", { abc:"abc" }, foo, "json");
}

Thank you.

thedp
  • 8,350
  • 16
  • 53
  • 95

3 Answers3

12

Yeah, already works. But you want it probably look like this:

function setVersion(feature, myFunction) {
      $.post("some.php", { abc:"abc" }, myFunction, "json");
}
setVersion(blah, foo);
elias
  • 1,481
  • 7
  • 13
2

Should run just fine.

I believe jQuery is actually meant to use the regular function, called by name. Using the anonymous function is simply a replacement for a named function that would otherwise be passed.

Eli
  • 97,462
  • 20
  • 76
  • 81
1

Yes, that is exactly how you do it.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005