leora
leora

Reputation: 196699

In javascript, how can I pass a function with parameter to be called later?

I have the following method in javascript:

  ShowPopupWithCallback("MyController/Load", alertCallback);

  function alertCallback()
  {
        alert("Ready");
  }  

  function ShowPopupWithCallback(url, callbackFunc)
  {
        $.post(url, function (data) {
            $("#myDialog").html(data);
            callbackFunc();
        }, "html");

  }

this works fine but I now want to pass in a parameter from the calling ShowPopupWithCallback method. something like:

  ShowPopupWithCallback("MyController/Load", alertCallback("My Message"));

  function alertCallback(message)
  {
        alert(message);
  }  

  function ShowPopupWithCallback(url, callbackFunc)
  {
        $.post(url, function (data) {
            $("#myDialog").html(data);
            callbackFunc();
        }, "html");

  }

but this DOESN"T seem to work as the alert is called right away (not after the ajay returns)

What is the right way to pass in a function to a method that includes it own parameters.

Upvotes: 1

Views: 89

Answers (3)

VladL
VladL

Reputation: 13043

You could use anonymous function for that:

ShowPopupWithCallback("MyController/Load", function(){ alertCallback("My Message");});

Upvotes: 2

T J
T J

Reputation: 43166

You can simply pass it as an additional argument

 function alertCallback(message)
  {
    alert(message);
  }  

function ShowPopupWithCallback(url, msg, callbackFunc)
  {
    $.post(url, function (data) {
        $("#myDialog").html(data);
        callbackFunc(msg);
    }, "html");
  }

ShowPopupWithCallback("MyController/Load", "My Message", alertCallback);

Upvotes: 0

plalx
plalx

Reputation: 43728

Use bind to perform partial function application.

ShowPopupWithCallback("MyController/Load", alertCallback.bind(null, "My Message"));

Upvotes: 2

Related Questions