我有一个用户控件,它可以让用户提供由特定事件的控件调用自己的脚本名称。

我有以下代码:

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包含一个函数,即,“FormatItem”的名称。这个例子是目前使用eval,我不想用...加上这个例子不反正工作,但我想我会表现出什么,我想要知道的。

在上面的例子中,得到了一个值未定义的错误为“项目”是一个字符串数组和eval试图将其转换成一个长的字符串。

如何实现此功能的任何仍然通过“项目”作为一个字符串传递数组到命名功能?

如果通过命名函数是一个坏主意,有什么办法?

这是我控制的声明方式:

<p74:WebAutoComplete runat="server" ID="ato_Test" AshxAddress="WebServices/SearchService.ashx" 
     FormatFunction="formatItem" SelectFunction="searchSelectedMaster" />
有帮助吗?

解决方案

me[me.get_formatFunction()](item);

其他提示

如果您的意图是所有参数传递给传递给formatItem(用户指定的功能),则代替使用的:

formatItem: function(item)
{
 return eval(me.get_formatFunction() + "(" + item + ");");
}

使用:

formatItem: function()
{
 return me.get_formatFunction().apply(me, arguments));
}

在apply()方法可被称为功能对象上,为了使用指定的“this”和参数数组以调用该函数。请参阅: http://odetocode.com/blogs/scott/archive/2007/07/04/function-apply-and-function-call-in-javascript.aspx 呼叫(的解释)和应用( )函数中的JavaScript。

那么你将要get_formatFunction()返回一个函数对象,而不是函数的名字;或者你可以尝试:

me[me.get_formatFunction()]

...得到这是由它的名字对“我”定义的函数。 (注意,如果get_formatFunction()返回字符串 'myFunc的',那么这相当于me.myFunc)

[编辑:改变引用 '这个' 使用 '我',而不是]

我不知道您的整个计划是什么,但你可以通过自己的,而不是他们的名字周围的功能:

function Foo(x, y) {
  // do something
}

function Bar(f, a, b) {
  // call Foo(a,b)
  f(a,b);
}

Bar(Foo, 1, 2);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top