JavaScript - How do I call a function from a string name and pass an array object?
-
20-09-2019 - |
Question
I've got a user control which lets users provided their own script names that are called by the control on specific events.
I have the following code:
initialize : function()
{
// Call the base initialize method
Point74.WebAutoComplete.callBaseMethod(this, 'initialize');
$(document).ready(
Function.createDelegate(this, this._onDocumentReady)
);
},
_onDocumentReady : function()
{
var me = this;
$("#" + me.get_id()).autocomplete(me.get_ashxAddress(),
{
formatItem: function(item)
{
return eval(me.get_formatFunction() + "(" + item + ");");
}
}
).result(me.get_selectFunction());
}
me.get_formatFunction contains the name of a function, i.e. "FormatItem". This example is currently using eval, which I do not want to use... plus this example doesn't work anyway, but I thought I'd show what I'm trying to get at.
In the example above, I get a value undefined error as 'item' is a string array and eval tries to convert it into one long string.
How can I achieve this functionality any still pass through 'item' as a string array to the named function?
If passing named functions is a bad idea, are there any alternatives?
This is how my control is declared:
<p74:WebAutoComplete runat="server" ID="ato_Test" AshxAddress="WebServices/SearchService.ashx"
FormatFunction="formatItem" SelectFunction="searchSelectedMaster" />
Solution
me[me.get_formatFunction()](item);
OTHER TIPS
If your intent is to pass all arguments to the user-specified function that are passed to formatItem(), then instead of using:
formatItem: function(item)
{
return eval(me.get_formatFunction() + "(" + item + ");");
}
Use:
formatItem: function()
{
return me.get_formatFunction().apply(me, arguments));
}
The apply() method can be called on a function object, in order to invoke that function using the specified "this" and argument array. See: http://odetocode.com/blogs/scott/archive/2007/07/04/function-apply-and-function-call-in-javascript.aspx for an explanation of the call() and apply() functions in javascript.
Then you will want get_formatFunction() to return a function object, rather than just the name of the function; or you can try:
me[me.get_formatFunction()]
...to get a function which is defined on 'me' by its name. (Note that if get_formatFunction() returns the string 'myFunc', then this is equivalent to me.myFunc)
[Edit: changed references to 'this' to use 'me' instead]
I'm not sure what your overall plan is, but you can pass functions around themselves instead of their names:
function Foo(x, y) {
// do something
}
function Bar(f, a, b) {
// call Foo(a,b)
f(a,b);
}
Bar(Foo, 1, 2);