假设我有两个脚本控件,一个控件将另一个作为子控件:

ParentControl : ScriptControl
{
   ChildControl childControl;
}

儿童控制的脚本:

ChildControl = function(element) 
{
  ChildControl.initializeBase(this, [element]);
}

ChildControl.prototype =
{
    callMethod: function()
    {
      return 'hi';
    },

    initialize: function() 
    {
      ChildControl.callBaseMethod(this, 'initialize');
    },

    dispose: function() 
    {
      ChildControl.callBaseMethod(this, 'dispose');
    }
}

在脚本方面,我想在子控件上调用一个方法:

ParentControl.prototype =
{
    initialize: function() 
    {
      this._childControl = $get(this._childControlID);
      this._childControl.CallMethod();

      ParentControl.callBaseMethod(this, 'initialize');
    },

    dispose: function() 
    {
      ParentControl.callBaseMethod(this, 'dispose');
    }
}

问题是,每次我尝试这个都说没有找到或支持这种方法。 ChildControl不能访问ChildControl上的所有方法吗?

我有什么办法让方法公开,以便ParentControl可以看到它吗?

<强>更新 是否可以“键入”? this._childControl?

这就是我问的原因......当我使用Watch时,系统知道ChildControl类是什么,我可以调用类本身的方法,但是,我不能调用相同的方法.- childControl宾语。你会认为如果内存中的类设计(?)识别出现有的方法,那么从该类实例化的对象也是如此。

有帮助吗?

解决方案

在客户端上,您通过将其传递给$ get来使用名为_childControlID的父控件对象的字段。这有一些问题:

  1. 如何设置_childControlID?我想通过在服务器上的父控件的描述符中添加它作为属性来猜测,但是您没有显示该代码,并且您没有在客户端父控件类上显示属性。
  2. $ get返回元素引用 - 而不是控件。因此,即使_childControlID设置为有效的元素ID,该元素也不会有一个名为CallMethod的方法。如果客户端子控件类在父控件之前初始化,则该元素将具有名为“control”的字段。您可以用来访问“附加”的脚本控件本身就是元素。这只适用于在父控件之前初始化子控件的情况。

其他提示

问题是“这个”。在javaScript中,这是指DOM对象。你需要做一些类似于使用Function.createDelegate时发生的事情,这在使用$ addHandler时是必需的(我知道你没有使用它,只是给出了上下文)。

你有两个选择。

  1. 您可以使用 $ find()找到您的子脚本控件。但是你会遇到在子控件之前初始化父控件的风险。

    this._childControl = $find(this._childControlID);
    this._childControl.CallMethod();
    
  2. 您可以使用 AddComponentProperty()在服务器上的控制描述符中注册属性。这将确保在初始化父控件之前初始化所有子控件。

    public class CustomControl : WebControl, IScriptControl
    {
         public ScriptControl ChildControl { get; set; }
    
         public IEnumerable<ScriptDescriptor> GetScriptDescriptors()
         {
             var descriptor = new ScriptControlDescriptor("Namespace.MyCustomControl", this.ClientID);
             descriptor.AddComponentProperty("childControl", ChildControl.ClientID);
    
             return new ScriptDescriptor[] { descriptor };
         }
    
         public IEnumerable<ScriptReference> GetScriptReferences()
         {
             var reference = new ScriptReference
                             {
                                 Assembly = this.GetType().Assembly.FullName,
                                 Name = "MyCustomControl.js"
                             };
    
             return new ScriptReference[] { reference };
         }
    }
    
  3. 然后只要你创建一个客户端属性“childControl”即可。它将自动初始化并准备在父控件init()方法中使用。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top