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

Exc*_*n e 22 javascript inheritance extjs prototypal-inheritance

在extjs中,你总是可以通过扩展extjs类constructor().对于从Component你那里学习的课程也可以延伸initComponent().

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

Bri*_*kau 18

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


yzo*_*org 12

让我尝试ExtJS版本4.0-4.2及更高版本的更新答案.

constructor()是对象/类之前创建方法.并且initComponent()show方法之前的组件.

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.
}
Run Code Online (Sandbox Code Playgroud)

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

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

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