3

我有以下一段完美运行的代码。

但是,我下面的项目列表将增长为数十个对象,我想知道是否可以删除 switch 子句并拥有更小和更少的代码行。

“type”参数是数组、视口、容器、网格面板等的类型,“component”参数是数组中的对象本身。

viewport: {},
container: {},
gridpanel: {},
panel: {},
treepanel: {},
window: {},
button: {},

add: function (component, type) {

    switch (component.getType() != undefined ? component.getType() : type) {
        case 'container':
            this.container[component.getId()] = component;
            break;
        case 'gridpanel':
            this.gridpanel[component.getId()] = component;
            break;
        case 'panel':
            this.panel[component.getId()] = component;
            break;
        case 'treepanel':
            this.treepanel[component.getId()] = component;
            break;
        case 'viewport':
            this.viewport[component.getId()] = component;
            break;
        case 'window':
            this.window[component.getId()] = component;
            break;
        case 'button':
            this.button[component.getId()] = component;
            break;
        default:
            break;
    }
},
4

2 回答 2

7

您可以使用括号表示法来引用组件类型:

add: function(component, type) {
    var componentType = component.getType() || type;
    this[componentType][component.getId()] = component;
}
于 2013-09-18T12:20:24.207 回答
2

除了 Frédéric Hamidi 的回答之外,您可能还想限制要引用的类型数量:

add: function(component, type) {
    var componentType = component.getType() || type;
    if (Ext.Array.indexOf([
        'container', 'gridpanel', 'panel', 'treepanel', 
        'viewport', 'window', 'button'
    ], componentType) !== -1) {
        this[componentType][component.getId()] = component;
    }
}
于 2013-09-18T12:34:36.447 回答