0

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

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');
    }
}

问题是,每次我尝试这都是说找不到或不支持这种方法。ParentControl 不应该可以访问 ChildControl 上的所有方法吗?

有什么方法我必须公开该方法以便 ParentControl 可以看到它?

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

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

4

3 回答 3

1

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

于 2008-12-30T20:36:30.553 回答
1

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

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

你有几个选择。

  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 };
         }
    }
    

然后,只要您创建一个客户端属性“childControl”,它将自动初始化并准备好在父控件的 init() 方法中使用。

于 2010-05-14T13:35:06.540 回答