在extjs中,您可以始终通过constructor()
扩展一个extjs类。对于从Component
派生的类,您还可以通过initComponent()
进行扩展。
我想知道为什么有那么多代码通过initComponent
进行扩展,而constructor
似乎是通用扩展方法。initComponent
相对于constructor
是否具有明显优势?
在extjs中,您可以始终通过constructor()
扩展一个extjs类。对于从Component
派生的类,您还可以通过initComponent()
进行扩展。
我想知道为什么有那么多代码通过initComponent
进行扩展,而constructor
似乎是通用扩展方法。initComponent
相对于constructor
是否具有明显优势?
首先,通过constructor
进行覆盖的能力比initComponent
晚出现在Ext的某个版本中,因此一定年龄段的代码将不得不使用initComponent。如今,如果你想要在基类的initComponent被调用之后(这对于constructor来说太早了)但在组件被渲染之前做任何事情,仍然需要覆盖initComponent。在许多情况下(比如最常见的设置配置),它们实际上都没有本质区别,大多数人会选择最方便的方法。但是,在某些情况下,这很重要。
让我尝试用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次。
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