Jon
Jon

Reputation: 1259

How can I pass the enclosing function as its own recursive callback in Javascript?

I'm designing an AJAXy form-generation Javascript library for a set of applications where callback behavior should vary based on the application. The API functions I'm exposing take a set of callbacks that attach functionality to the various buttons and other events that occur within the standard form:

For example, one application wants to render this form within a new pop-up, while another wants it inline in an existing page. In the pop-up scenario, the onSaveCallback will close the pop-up and post a message to the launching page. In the inline scenario, the onSaveCallback should reload the form content by re-running the function.

Is there a standard, simpler way of doing that recursive callback that's not writing the function twice, like the following?

MyFormLibrary.displayForm(
  div, 
  formName, 
  query,
  onLoadCallback,
  function onSaveCallback(result) {
      MyFormLibrary.displayForm(
         div,
         formName,
         query,
         onLoadCallback,
         onSaveCallback,
         onCancelCallback,
         busyCallback,
         readyCallback);
  },
  onCancelCallback,
  busyCallback,
  readyCallback);

Upvotes: 0

Views: 204

Answers (2)

Gabriel S.
Gabriel S.

Reputation: 1943

Put your call inside a function so you can call it recursively:

function recursiveSaveCallback (result) {
    MyFormLibrary.displayForm(
        div, 
        formName, 
        query,
        onLoadCallback,
        recursiveSaveCallback,
        onCancelCallback,
        busyCallback,
        readyCallback
    );
}

recursiveSaveCallback(result);

Upvotes: 0

Mike Samuel
Mike Samuel

Reputation: 120556

Give it a name. In the case above, you call it onSaveCallback inside. Just use that name for the outer function, and refer to it as onSaveCallback. arguments.callee should work as well if there's a reason you can't give it a name.

MyFormLibrary.displayForm(
  div, 
  formName, 
  query,
  onLoadCallback,
  arguments.callee,
  onCancelCallback,
  busyCallback,
  readyCallback);

Upvotes: 2

Related Questions