如何在 Ext.define 中实现 IF 语句

How to implement IF statement in Ext.define

我已经定义了我的面板class,我想根据具体情况对其进行自定义,例如以下伪代码:

if (foo =='A') {
   //Draw only button1
}
else {
   //Draw button1 & button2
}

但是,我不知道如何在 MyPanel 中包含这个 if 语句 class。

Ext.define('MyApp.view.Main', {
    extend : 'Ext.panel.Panel',
    xtype  : 'main',
    width: 500,
    height: 400,

    items:[{
        xtype: 'mypanel',
        html: 'This is panel1',
        foo: 'A',
    },{
        xtype: 'mypanel',
        html: 'This is panel2',
        foo: 'B',
    }]
});
Ext.define('MyApp.view.MyPanel', {
    extend : 'Ext.panel.Panel',
    xtype  : 'mypanel',

    initComponent: function () {
        foo = this.foo;
        this.callParent(arguments);
    },

    header: {
        items: [{
            xtype: 'button',
            text:  'button1',
        },{
            xtype: 'button',
            text:  'button2',
        }]
    },

    width: 500,
    height: 200,
});

我准备了一份Fiddle example

提前致谢。

只需在'initComponent'方法中设置header属性或使用特殊方法return'header'配置object取决于条件。

Ext.define('MyApp.view.MyPanel', {
    extend: 'Ext.panel.Panel',
    xtype: 'mypanel',

    initComponent: function () {
        foo = this.foo;
        this.header = {
            items: [{
                xtype: 'button',
                text: 'button1'
            }, {
                xtype: 'button',
                text: 'button2',
                hidden: (foo === 'A'),
            }]
        };
        this.callParent(arguments);
    },
    width: 500,
    height: 200,
});

使用特殊方法:

Ext.define('MyApp.view.MyPanel', {
    extend: 'Ext.panel.Panel',
    xtype: 'mypanel',

    initComponent: function () {
        this.header = this.getMyCustomHeader();
        this.callParent(arguments);
    },
    
    getMyCustomHeader: function () {
        var customHeader = {
            items: [{
                xtype: 'button',
                text: 'button1'
            }, {
                xtype: 'button',
                text: 'button2'
            }]
        }
        if (this.foo === 'A') {
            customHeader = {
                items: [{
                    xtype: 'button',
                    text: 'button1'
                }]
            }
        }
        return customHeader;
    },
    width: 500,
    height: 200
});