in my project, I register different functions (having different number of arguments) as listeners to a number of events. When the event takes place, I need to fire the associated function. I receive the parameters to be passed to listener method in the form of an array whereas the listener function expect each separate argument. So, I am doing it like this but I do not like the approach and would like to know if there is an elegant way of doing it,
function callListenerWithArgs(func, args){
switch(args.length){
case 1:
func(args[0]);
break;
case 2:
func(args[0], args[1]);
break;
case 3:
func(args[0], args[1], args[2]);
break;
case 4:
func(args[0], args[1], args[2], args[3]);
break;
default:
func();
}
}
Use .apply
If you need to bind to a specific scope, you can pass another argument in to use as
thisinside the function:Also, a nuance of JavaScript is that you can call functions with undefined values. So making a small tweak to your existing code will work in 95% of all cases (this isn’t suggested as a solution, just pointing it out):
If your
funcis defined as:you get
a,b,cpassed in, along with some moreundefinedvalues that get ignored. As I said above, this works in 95% of cases. It doesn’t work if you ever checkarguments.lengthin the called function since it will always be the same, regardless of the number of parameters the function defines.