Polymer 2.0 too many ifs

230 Views Asked by At

I'm looking for a better optimized solution to have too many if's in Polymer 2.0. For example i'm building a table object, where each cell can be text, buttons, links, objects, ect. I want the user to be able to enter a 2D array and have the Polymer 2.0 object be able to pick which markup to use. My current solution (below) simple has several if statements, but this means that every cell if going to call each statement. Is there a a better way to handle this?

<template is="dom-if" if="[[matchCellType(cell, 'button')]]">
    <UI-Button id='[[cell.button.ID]]' class$='[[cell.button.class]]'>[[cell.button.text]]</UI-Button>
</template>
<template is="dom-if" if="[[matchCellType(cell, 'object')]]">
    <span class="object-toggle"></span>[[cell.title]]
    <div class="properties">
        <template is="dom-repeat" items="[[getProps(cell)]]">
            <div class="properties_row"><div class="properties_cell"><b>[[item.title]]:</b></div><div style="display: table-cell">[[item.val]]</div></div>
        </template>
    </div>
</template>
<template is="dom-if" if="[[matchCellType(cell, 'link')]]">
    <a target="_blank" href='[[cell.link.href]]'>[[cell.link.text]]</a>
</template>
<template is="dom-if" if="[[matchCellType(cell, 'cell')]]">
    [[cell]]
</template>
<template is="dom-if" if="[[matchCellType(cell, 'textArea')]]">
    <ui-text-area rows="[[cell.textArea.rows]]" cols="[[cell.textArea.cols]]" id='[[cell.textArea.id]]' class$='[[cell.textArea.class]]' text=    [[cell.textArea.text]]></ui-text-area>
</template>
1

There are 1 best solutions below

2
On

Lots of calls to matchCellType don't harm if it isn't a costly computation (if it were, you could update a property in an observer and test on the property instead)

Factor out the series of ifs into a component so you don't clutter up your table

As an alternative to using dom-ifs, compute an attribute or style class from the cell, render all elements always, and use CSS to have only the matching elements be visible. This produces much more DOM elements, but may still be more performant because browsers handle hidden or display:none elements very efficiently

Instead of stamping with several dom-ifs, you could create and remove nodes imperatively