1

我有一个动态配置其项目的视图。这些子项也动态配置自己。

我正在尝试使用 initComponent,但在下面的代码中,仅在 childItem 上存在 initComponent 就会导致错误(“无法读取未定义的属性'长度'”)。

在 childItem 上没有 initComponent,其余的工作。

这有什么问题?有替代方法吗?

Ext.define('myapp.view.MyView', {
    extend: 'Ext.container.Container',

    initComponent: function () {
        var me = this;

        var childItem = {
            xtype: 'container',

            initComponent: function () {
                var me = this;
                // I want the childItem to do some configuration here.
                me.callParent();
            }
        };

        me.items = [
            childItem
        ];

        me.callParent();
    }
});
4

3 回答 3

3

您可以xhooks为组件使用未记录的配置。看到这个

Ext.ComponentManager.create({
    xtype: 'panel',
    xhooks: {
        initComponent: function() {
            console.log('in local override for this specific instance of panel');
            this.items = [{
                xtype: 'panel',
                xhooks: {
                    initComponent: function() {
                        console.log('in local override for this specific instance of panel');
                        this.items = [{html: 'hi'}];
                        this.callParent();
                    }
                }
            }];
            this.callParent();
        }
    }
}, 'panel');

在组件创建过程中,当 Ext 看到一个属性时,它会使用配置中包含的匹配函数xhooks覆盖当前实例的xhooks函数。这确保了它的callParent工作原理。

于 2013-08-22T17:51:20.083 回答
2

您没有在代码中正确扩展 Ext.Container。如果要覆盖initComponent,请先使用Ext.define定义您的类:

Ext.define('MyContainer', {
    extend: 'Ext.Container',
    alias: 'widget.my-ct',

    initComponent: function () {
        var me2 = this;
        // I want the childItem to do some configuration here.
        me2.callParent();
    }
});

Ext.define('myapp.view.MyView', {
    extend: 'Ext.container.Container',

    initComponent: function () {
        var me = this;

        var childItem = {
            xtype: 'my-ct'
        };

        me.items = [
            childItem
        ];

        me.callParent();
    }
});

编辑:

作为最佳实践,您应该始终在单独的文件中定义您的类。我认为这是常识,只是想解释为什么您的原始代码有错误,但评论部分抱怨说,所以我已将其更改为使用更合适的代码。

于 2013-08-21T11:59:25.370 回答
0

callParent仅适用于已通过的方法Ext.define(或类似的方法)。在这里,您正在执行“运行时”覆盖,因此callParent不适用于孩子。

您对下一个开发人员最友好的选择是将这些转换为合法的 Ext 覆盖。为简单起见,您可以使用匿名类。例子:

var childClass = Ext.define(null, {
    extend: 'Ext.container.Container'

    ,initComponent: function() {

        // Here that will work
        this.callParent(arguments);
    }
});

var childItem = new childClass;

// ...

另一种选择是callParent通过在正确的范围内调用父方法来完成自己的工作。这里的问题是您必须知道如何访问父方法,但是这个选项非常适合吹嘘您的 javascript 技能,因为它会导致大多数(非 javascript)开发人员无法弄清楚的一些野蛮语法;)在您的情况下,将this.callParent()您的孩子替换为:

Ext.container.Container.prototype.initComponent.apply(this, arguments);

在这两种情况下,不要忘记你必须 require Ext.container.Container。在第一种情况下,这将确保代码同步运行,在第二种情况下,它将避免它在未定义的类上崩溃。

于 2013-08-21T12:02:07.640 回答