I am currently implementing a data-table element using custom elements (web components). The table can have different types of cells (text, number, date, etc) that are used to render each row.
E.g
<my-table>
<my-table-cell-text column="name"></my-table-cell-text>
<my-table-cell-date column="dob" format="YYYY-MM-DD"></my-table-cell-date>
<my-table-cell-number column="salary" decimals="2"></my-table-cell-number >
</my-table>
I also have a MyTableCell
class which all cell elements extends. This works fine for sharing common functionality, however styling can be a pain, because each cell type is its own html tag. Currently, I am adding a css class when extending MyTableCell
, but for argument's sake, lets say I don't want to do that.
The ideal solution would be to be able to extend a custom element, using the is
keyword, e.g <my-table-cell is="my-table-cell-text">
, but that's only allowed for built in html elements.
I can think of 3 approaches of solving this issue:
Have syntax similar to
<input type="">
, but that's a lot more work, since you are no longer extending a base class, but rather creating variations of the same element and this means you need a custom way of registering the different variations, something like a staticMyTableCell.registerType
A composable approach, where I wrap a renderer element,
<my-table-renderer-text>
, inside a generic<my-table-cell>
. This avoids the custom register method, but it's harder to write and results in more elements and more boilerplate code, which in turn means a performance hit.A mix of both, where the user writes
<my-table-cell type="text">
and the cell uses something likedocument.createElement('my-table-rendener-'+ type)
internally. This keeps the simpler syntax of option 1, while still avoiding the custom register method, but it has the same performance implications of option 2.
Can you suggest any better alternatives? Am I missing anything?
NB: This answer is separeted from the other as it's quite extensive by itself and totally independant.
If you use Autonomous Custom Elements (i.e. custom tags) with a (optionnal)
type
attribute:...you could use the MVC pattern:
Example with generic and string view:
In the custom element definition (which can be viewed as the Controller):
Example with a Custom Element v1 class:
Below is a live snippet:
What could be done is using
<td>
Customized Built-in Element:All extensions share the same prototype ancestor. Example:
This way all cells extend the same
<td>
element, share a common prototype but have their own method implementations.You can override shared method, and shared method can call specific method of the derived prototype object.
See a running example here:
Note: If you don't want type extension you can also do it with custom tags. The idea is to have a common prototype and different custom elements that share it (thanks to standard prototype inheritance).