Pass an arbitrary number of parameters to a JavaScript function

My JavaScript code is hardly an Ajax request that expects XML to be returned from the source code. The back-end can return execute_callbackas one of the XML tags, for example:

<?xml version="1.0" encoding="windows-1251"?>
<response>
    <execute_callback>
        <function_name>someFunction</function_name>
    </execute_callback>
</response>

And everything is in order, as far as you know the exact number of parameters expected by this callback. But what if the back-end 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 to pass parameters 10.2 and 'some_text' to someFunctionand JSON {x: 1, y: 2} to otherFunction?

I know an ugly solution (using a function arguments), but I'm looking for a beautiful one.

: XML - :) , , - , JavaScript. Python, :

def somefunc(x, y):
    print x, y
args = { 'x' : 1, 'y' : 2 }
somefunc(**args)

JavaScript.

+5
3

Function.apply. , (window ).

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
}
+5

:

function someFunction(){
    for(i = 0; i < arguments.length; i++)
        alert(arguments[i]);
}

Javascript , , javascript .

someFunction(1, 2, 'test', ['test', 'array'], 5, 0);

- .

+8

Instead of calling a function, refer to your function as an element in an associative array by name:

var funcName = // parse your xml for function name
var params = new Array();
params[0] = 10.2; // from your parsed xml
params[1] = 'some text'; // also from your parsed xml

// functions are attached to some Object o:

o[funcName](params); // equivalent to o.funcName(params);

I wrote an example above: http://jsbin.com/ewuqur/2/edit

0
source

All Articles