Create a Custom Element with different sub-types

前端 未结 2 962
长发绾君心
长发绾君心 2020-12-11 08:38

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

2条回答
  •  不知归路
    2020-12-11 09:08

    What could be done is using Customized Built-in Element:

    Bob
    11/1/2017 44

    All extensions share the same prototype ancestor. Example:

    //common cell
    class DataCell extends HTMLTableCellElement {...}
    
    //typed cell
    class StringCell extends DataCell {
        renderContent() { ... }
    } 
    customElements.define( 'data-string', StringCell, { extends: 'td' } )
    

    This way all cells extend the same 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:

    //table
    class DataTable extends HTMLTableElement {
        constructor() { 
            super()
            console.info( 'data-table created' )
        }
    } 
    customElements.define( 'data-table', DataTable, { extends: 'table' } );
    
    //cell
    class DataCell extends HTMLTableCellElement {
        connectedCallback() { 
            console.info( 'cell connected' )
            if ( typeof this.renderContent === 'function' ) 
                this.renderContent()
        }
    } 
    
    //cell string
    class StringCell extends DataCell {
        renderContent()
        {
            console.info( 'data-string render' )
            this.innerHTML = '"' + this.textContent.trim() + '"'
        }
    } 
    customElements.define( 'data-string', StringCell, { extends: 'td' } )
    table {
        border-collapse: collapse ;
    }
    td, th {
        border: 1px solid gray ;
        padding: 2px
    }

    Test Table Extension v1

    Id Name Age
    1 An 20
    2 Bob 31

    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).

    提交回复
    热议问题