Reputation: 7341
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
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
Reputation: 328556
I can think of several approaches:
You can split the string and use eval(name+'()')
in each name in the list. Note that eval()
can be evil, security wise.
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).
Use an anonymous function:
cloneDetails(thisID, function(){
initialiseDates();
doSomethingElse();
doAnotherThing();
});
I like the last approach because:
Upvotes: 1