代码之家  ›  专栏  ›  技术社区  ›  Exception e

Extjs:通过构造函数或initComponent扩展类?

  •  22
  • Exception e  · 技术社区  · 14 年前

    在extjs中,您可以通过 constructor() . 对于派生自的类 Component initComponent()

    initComponent ,鉴于 constructor 似乎是通用的扩展方法。做 建造师 ?

    3 回复  |  直到 14 年前
        1
  •  17
  •   Brian Moeskau    14 年前

    首先,通过 constructor 已添加到比 initComponent ,所以某个年龄段的所有代码都必须使用initComponent。现在,如果您想做任何事情,您仍然会重写initComponent 之后 将渲染组件。在许多情况下(像最常见的,设置configs),这两种方式实际上都无关紧要,大多数人做任何最方便的事情。然而,在某些情况下,这一点很重要。

        2
  •  12
  •   yzorg    11 年前

    让我尝试一下extjs4.0-4.2及更高版本的更新答案。

    这个 constructor() 方法。以及 initComponent() 是组件吗

    constructor: function(config) {
      // ctor #1 - insert code here to modify config or run code to inject config
      // probably the cheapest place to make changes - before anything has been built
    
      this.callParent(arguments);
    
      // ctor #2 - insert code here if you need to make changes 
      // after everything has been rendered and shown, IIUC
    },
    initComponent: function() {
      // this function runs between ctor #1 and ctor #2
    
      // initComponent #1 - the UI component object tree is created,
      // (this object and child objects from config { items: [{...}]})
      // but they have not yet been rendered to DOM or shown.
    
      this.callParent(arguments);
    
      // initComponent #2 - I believe this is equivalent to ctor #2, 
      // I would prefer ctor as it is more universal.
    }
    

    具有子级或复杂布局的面板您可能需要使用initComponent,因为您需要检查和操作组件(UI对象图)。

    但是对于单个表单元素(combobox、button等),我坚持使用构造函数,我认为它更轻(在任何复杂的对象构造或DOM更改之前),而且更通用。IOW构造函数可以用于简单的UI、模型和数据存储;后两者不能使用initComponent。

    所以我只在有理由的时候才使用initComponent。通常,当我编写initComponent函数时,我尝试操作子UI对象,下一步是将该子控件提取到它自己的Ext.define()中,移动自定义代码以在子控件类中运行,这将从父面板中删除复杂的init。这个过程我在最近的一页中已经重复了4次。

        3
  •  2
  •   Eddie C.    6 年前

    以下是Jay Garcia在《ExtJS在行动》一书中的一些相关引用:

    稍后,鉴于构造函数是将配置参数应用于实例的地方:

    如果子类的配置实例需要通过cloneConfig进行克隆,那么通过构造函数进行扩展是最好的选择。

    顺便说一句,尽管Jay的书是关于ExtJS3的,但是cloneConfig似乎仍然与ExtJS4相关;请参见:

    http://docs.sencha.com/ext-js/3-4/#!/api/Ext.Component-method-cloneConfig

    http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Component-method-cloneConfig