Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refering to Object from String

I have the following piece of code which works perfectly.

However, my list of items below is going to grow to become tens of objects and I want to know if it is possible to remove the switch clause and have something smaller and fewer lines of code.

the 'type' argument is the type of the array, viewport, container, gridpanel, etc. and the 'component' argument is the object itself which goes in the array.

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;
    }
},
like image 236
hermann Avatar asked Mar 19 '26 20:03

hermann


1 Answers

You can use bracket notation to refer to the component type:

add: function(component, type) {
    var componentType = component.getType() || type;
    this[componentType][component.getId()] = component;
}
like image 174
Frédéric Hamidi Avatar answered Mar 22 '26 10:03

Frédéric Hamidi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!