Jamie Hartnoll
Jamie Hartnoll

Reputation: 7341

How can I pass a string, or list of function names to be processed as callbacks in Javascript

Done a bit of Googling, but not quite finding what I want.

In an effort to reduce the amount of JAvascript lines my applications requires, I am trying to use as many reusable functions as possible.

The problem of course is trying to make these functions and flexible as possible.

So I have a form which is dynamically expanded by a cloning function using jQuery. In order for this to work, there are a few additional functions which need to run, for example, to correctly initialise datepickers, on the dynamically created elements.

These requirements are different depending upon which form is being cloned.

So, I call my cloning function as follows:

$('.button').click(function (){
    var thisID = $(this).attr('id').replace('add', '');
    cloneDetails(thisID, initialiseDates);
});

The cloneDetails function looks like this:

function cloneDetails(cur_num, callBackFunctions) {

  /// do loads of stuff ///

 callBackFunctions();

});

In this instance, the cloning function will run and do what it needs, then it'll run a second function call initialiseDates

What I want to be able to do though is specify several function names to run after the cloning function, with a call such as

cloneDetails(thisID, 'initialiseDates, doSomethingElse, doAnotherThing');

So, stating a list of functions to run after the cloneDetails function has been run.

I don't think I am setting up the callBack method correctly, and don't know how I should be.

Help much appreciated.

EDIT: I don't want to bundle all these functions into a single function, the whole point is these functions should all be useable independently and/or together.

Upvotes: 0

Views: 140

Answers (2)

forivall
forivall

Reputation: 9891

Another option (if you're using jQuery > 1.7): You can use the jQuery.Callbacks function.

cloneDetails(thisID, $.Callbacks()
    .add(initialiseDates, doSomethingElse, doAnotherThing));

function cloneDetails(cur_num, callBackFunctions) {

  /// do loads of stuff ///

  callBackFunctions.fire();

});

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328556

I can think of several approaches:

  1. You can split the string and use eval(name+'()') in each name in the list. Note that eval() can be evil, security wise.

  2. Instead of a string, why not pass the functions as an array? Simply iterate over arguments[1..n] (arguments is an automatic variable which contains all function arguments).

  3. Use an anonymous function:

    cloneDetails(thisID, function(){
        initialiseDates();
        doSomethingElse();
        doAnotherThing();
    });
    

I like the last approach because:

  1. It's the most flexible
  2. Readable
  3. Only adds a few bytes of code where you need them
  4. Most performant

Upvotes: 1

Related Questions