23

在 extjs 中,您始终可以通过constructor(). 对于从Component你派生的类,也可以通过扩展initComponent()

我想知道为什么这么多代码通过扩展initComponent,而constructor似乎是通用扩展方法。是否initComponent提供明显优势constructor

4

3 回答 3

18

constructor首先,在更高版本的 Ext than 中添加了覆盖 via 的功能initComponent,因此特定年龄的所有代码都必须使用 initComponent。这些天来,如果你想在基类 initComponent 被调用之后做任何事情,你仍然会重写 initComponent (构造函数对于这个来说太早了),但组件被渲染之前。在许多情况下(如最常见的设置配置),这实际上并不重要,大多数人都会做最方便的事情。但是,在某些情况下它很重要。

于 2010-07-03T17:35:32.460 回答
12

让我根据 ExtJS 版本 4.0-4.2 及更高版本尝试更新答案。

是创建方法之前的constructor()对象/类。并且是show方法 之前的组件。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 对象图)。

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

So I only use initComponent when there's a reason to do so. Often when I write an initComponent function I'm trying to manipulate child UI objects, and my next step is to extract that child control into its own Ext.define(), the move the custom code to run in the child control class, which removes the complex init from the parent panel. This process I've repeated 4 times in my latest page.

于 2013-07-12T14:19:36.753 回答
2

以下是 Jay Garcia 的 ExtJS in Action 一书中的一些相关引述:

initComponent 在 Component 类的构造函数中执行,但只有在对 Component 进行了一些关键的设置任务之后才会执行。这些任务包括配置对象属性的缓存和应用到类的实例

后来,鉴于构造函数是将配置参数应用于实例的位置:

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

顺便说一句,尽管 Jay 的书是关于 ExtJS 3 的,但似乎 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

于 2012-01-03T22:07:54.680 回答