项配置中的EXTJS内联initComponent方法

EXTJS inline initComponent method within items config

本文关键字:内联 initComponent 方法 EXTJS 配置      更新时间:2023-09-26

免责声明:我对ExtJS(5.01版)还比较陌生。我希望能联系到一些ExtJS专家,为我指明正确的方向:在items配置中指定initComponent方法时出错。以下代码生成错误:

"未捕获的类型错误:无法读取未定义"的属性"items"

当北部子面板的"initComponent"函数被注释掉时,错误就会消失。我感觉我在初始化顺序上错过了一些东西。

Q:如何在items配置中指定子项initComponent方法?

Ext.define('MyApp.view.TestView', {
    extend: 'Ext.panel.Panel',
    title: 'Parent',
    height: 300,
    layout: 'border',
    items: [{
        xtype: 'panel',
        region: 'north',
        title: 'North Child',
        /* Problematic function: If commented, it works */
        initComponent: function(){
            console.log("test north child");
            this.callParent(arguments);
        }
    }],

    initComponent: function(){
        console.log("Test parent");
        this.callParent(arguments);
    }
});

简短的回答:您不能在孩子身上定义initComponent,因为您不能在那里做任何其他地方无法做的事情。

InitComponent是在创建组件"MyApp.view.TestView"的实例时执行的(您仅在此处使用Ext.define定义了它)。它可以使用Ext.create('MyApp.view.TestView',{创建,也可以通过创建另一个将该组件添加为项的视图,或者通过派生另一个组件(extend:'MyApp.view.TestView')来创建。

所有子组件都是在创建"MyApp.view.TestView"时创建的,因此子组件上的initComponent函数是多余的,因为没有父组件就无法创建子组件,因此父组件的initComponent可以用于您想在子组件的initComponent。

如果你需要在添加项目之前计算某事,你可以按照以下步骤进行:

Ext.define('MyApp.view.TestView', {
    extend: 'Ext.panel.Panel',
    title: 'Parent',
    height: 300,
    layout: 'border',
    initComponent: function(){
        var me = this,
            tf = Ext.getCmp("someTextField"),
            myTitle = (tf?tf.getValue():'');
        Ext.applyIf(me,{
            items: [{
                xtype: 'panel',
                region: 'north',
                title: myTitle,
            }]
        });
        this.callParent(arguments);
    }
});

请参阅文档Ext.applyIf的具体功能(以及它与Ext.apply的区别,因为该功能有时也很方便)。