Lit-element: Accesing element instances

Created on 20 May 2018  路  2Comments  路  Source: Polymer/lit-element

What is the recommended approach for retrieving instances of elements after they are instantiated?
My questions arises from the need of having configurable properties on classes/elements.
In some cases it is undesirable to specialize (using implementation inheritance) a class. Let us assume we only need to change one property or method in each sub class, in e.g:
class DataTable extends LitElement
class ProductDataTable extends DataTable
class UserDataTable extends DataTable

In this example all the tables have the same behavior except of how the data is fetched. If I could pass a custom fetch function to each DataTable my problem would be solved. Having access to the element instance of the DataTable this would be no issue. If I create an element by placing the custom HTML element tag in the DOM <data-table></data-table>, is the preferred way to query the element directly from the DOM (in e.g. document.querySelector())?

Or should I create an instance of the element programmatically and then insert it in the appropriate place?

const table = new DataTable(...);
table.fetch = getAllUsers; // Or pass it to the constructor as a dependency
document.body.appendChild(table);

Most helpful comment

If the table is defined as part of an element, I wouldn't use document selector but rather this.shadowRoot.gerElementById or this.shadowRoot.querySelector. That way you're querying inside the dom of your element rather than the entire document.

All 2 comments

There's nothing wrong with using querySelector, but getElementById would probably be better. I question the need to create separate custom elements based on the nature of the fetch though - I think it would be better to separate the data retrieval from the visual display of the data. i.e. Your generic DataTable element has an items/row property (array of data objects) and a way of defining column bindings to the supplied data.

<data-table id="myTable">
    <data-table-column caption="First Name" field="firstName"></data-table-column>
    <!-- Other Columns -->
</data-table>
let table = document.getElementById('myTable');
table.items = getAllUsers();

If the table is defined as part of an element, I wouldn't use document selector but rather this.shadowRoot.gerElementById or this.shadowRoot.querySelector. That way you're querying inside the dom of your element rather than the entire document.

Was this page helpful?
0 / 5 - 0 ratings