elref
EXPERIMENTAL
TODO: tests, types, compatibility (currently requires ES6 support, Proxies)
Adds this.el
to a custom element, allowing the definition of internal element references via ref="<name>"
HTML attrs placed on child elements. Child elements are then accessible at this.el.<name>
.
this.el
provides getters at every key that will lazily query the parent for the first child element with a matching ref="<name>"
attribute (undefined
if no matching children are found).
this.el.list.<name>
behaves similarily but queries for all matching children and returns an array (empty array if no matching children are found).
Results will be cached and returned as long as they are still attached to DOM
An example is worth a thousand words (LitElement used for HTML-rendering simplicity):
; { super...arguments; thisel = this; } { return html` `; } async { await thisupdateComplete; console; // --> <div ref="foo"> console; // --> [ <div ref="bar">, <div ref="bar"> ] // lazy querying - queries are not executed until these calls and results are cached // you can also store custom values under this.el: thiselall = thiselfoo ...thisellistbar; console; // --> [ <div ref="foo">, <div ref="bar">, <div ref="bar"> ] // now we can easily iterate over all our elements: console; // --> ["foo", "bar", "bar"] }
It's also possible to "scope" and "select" for greater control over querying. This can be useful when your HTML is generated by some external means and you are unable to add ref attributes easily.
; { super...arguments; thisel = this; } { thischart; // chart rendering handled externally... // Resulting HTML: // <div class="chart-container"> // <svg> // <g class="plot-area">...</g> // <g class="axis x">...</g> // <g class="axis y">...</g> // </svg> // </div> } async { await thisupdateComplete; const svg = thiselsvg; // query for svg thisel scopesvg // from here on in the chain queries only operate within `svg` // query for plot area element list; // query for axis elements console; // --> <g class="plot-area"> console; // --> [ <g class="axis x">, <g class="axis y"> ] }
Usable as a mixin:
; LitElement // no constructor override necessary ...
OR
;; LitElement // no constructor override necessary ...