My JavaScript code is barely an Ajax request that expects XML to be returned from back-end. The back-end can return execute_callback
as one of XML tags like this:
<?xml version="1.0" encoding="windows-1251"?>
<response>
<execute_callback>
<function_name>someFunction</function_name>
</execute_callback>
</response>
And everything is okay as far as you know the exact number of parameters this callback
expects. But what if the back-end has returned
<?xml version="1.0" encoding="windows-1251"?>
<response>
<execute_callback>
<function_name>someFunction</function_name>
<param>10.2</param>
<param>some_text</param>
</execute_callback>
<execute_callback>
<function_name>otherFunction</function_name>
<param>{ x: 1, y: 2 }</param>
</execute_callback>
</response>
How do I now pass parameters 10.2 and 'some_text' to someFunction
and JSON { x: 1, y: 2 } to otherFunction
?
I know an ugly solution (using function's arguments
), but I am looking for a pretty one.
And before I forget: don't parse the XML for me - I can do that on my own :) All I need is somewhat of a trick to pass an arbitrary number of arguments to a function in JavaScript. If you know Python, I want:
def somefunc(x, y):
print x, y
args = { 'x' : 1, 'y' : 2 }
somefunc(**args)
but in JavaScript.
The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don't know how many arguments will be sent to the function.
When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit.
In javascript, you can call a function with an arbitrary number of arguments. A function can be defined with any number of arguments. If extra arguments are present, it does not matter and will be simply ignored. function greetings(name){ console.
Unless otherwise specified in the description of a particular function, if a function or constructor described in this clause is given more arguments than the function is specified to allow, the extra arguments are evaluated by the call and then ignored by the function.
You can just pass them all into your function:
function someFunction(){
for(i = 0; i < arguments.length; i++)
alert(arguments[i]);
}
Javascript functions have an arguments array-like object, and it is syntactically correct to call a javascript function with any number of arguments.
someFunction(1, 2, 'test', ['test', 'array'], 5, 0);
is a valid call to that function.
You could refer to Function.apply. Assuming the callback functions are declared in global object (window
in browser).
var callback_function = window[function_name];
if (callback_function) { // prevent from calling undefined functions
callback_function.apply(window, params); // params is an array holding all parameters
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With