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

23

在extjs中,您可以始终通过constructor()扩展一个extjs类。对于从Component派生的类,您还可以通过initComponent()进行扩展。

我想知道为什么有那么多代码通过initComponent进行扩展,而constructor似乎是通用扩展方法。initComponent相对于constructor是否具有明显优势?

3个回答

18

首先,通过constructor进行覆盖的能力比initComponent晚出现在Ext的某个版本中,因此一定年龄段的代码将不得不使用initComponent。如今,如果你想要在基类的initComponent被调用之后(这对于constructor来说太早了)但在组件被渲染之前做任何事情,仍然需要覆盖initComponent。在许多情况下(比如最常见的设置配置),它们实际上都没有本质区别,大多数人会选择最方便的方法。但是,在某些情况下,这很重要。


好的,我将默认使用构造函数作为扩展方法。当我需要通过initComponent进行覆盖时,这意味着我与类的内部(过于)亲密了。 - Exception e
1
我也发现这个链接非常有帮助:http://www.sencha.com/forum/showthread.php?139162-clarification-about-initComponent-constructor-callParent - clint
1
我将此降级,因为回答者是ExtJS的原始开发人员之一,但仍然以“但是,在某些情况下确实很重要”结束他的回答,然后没有告诉我们哪些情况。在我看来,这根本不是对原始问题的回答——在它很重要的情况下可能会提供对OP的查询“initComponent是否提供明显优势”的见解。 - Dexygen
既然你们都对这个主题非常了解,那么你们对这种扩展类和覆盖方法的格式有何感想? - blong

12

让我尝试用ExtJS 4.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更改之前)并且更通用。也就是说,构造函数可以用于简单的UI、模型和数据存储;后两者不能使用initComponent。

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


2
以下是Jay Garcia的书《ExtJS in Action》中的一些相关引用:
initComponent是在Component类的构造函数内执行的,但仅在组件的一些关键设置任务完成后才执行。这些任务包括将配置对象属性缓存和应用于类实例。
稍后,在考虑构造函数是哪里应用配置参数到实例时:
如果子类的配置实例需要通过cloneConfig进行克隆,则通过构造函数进行扩展是最佳选择。
顺便说一句,尽管Jay的书是关于ExtJS 3的,但看起来cloneConfig在ExtJS4中仍然相关,请参见:

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

and

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接