Directive のインスタンスは内部的に作成されるので 作成時にホストの要素を constructor に渡せない
directive 関数を呼び出すときに継承した新しいクラスを作って host プロパティにホスト要素を入れるようにする
更新の場合は Directive の constructor は呼び出されず render のみ呼び出される
一旦 DOM が削除されるような場合は再度作成されたときにまた Directive が作られる
| import {html, LitElement} from "lit" | |
| import { directive, Directive } from "lit/directive.js" | |
| const customElementDirective = (element, Directive) => { | |
| return directive( | |
| class extends Directive { | |
| host = element | |
| } | |
| ) | |
| } | |
| class Dire extends Directive { | |
| host = null | |
| constructor() { | |
| super() | |
| console.log("Directive created") | |
| } | |
| render(name) { | |
| console.log("Directive rendered", this.host, name) | |
| return "a" | |
| } | |
| } | |
| class ExampleElement extends LitElement { | |
| static properties = { | |
| n: {} | |
| } | |
| constructor() { | |
| super() | |
| this.d = customElementDirective(this, Dire) | |
| this.n = 0 | |
| } | |
| render() { | |
| return html` | |
| <button @click=${() => this.n++}>${this.n}</button> | |
| <div>${this.d("A")}</div> | |
| ${this.n % 2 === 0 | |
| ? html`<div class=${this.d("B")}>${this.d("C")}</div>` | |
| : null | |
| } | |
| ` | |
| } | |
| } | |
| customElements.define("example-element", ExampleElement) |
Directive のインスタンスは内部的に作成されるので 作成時にホストの要素を constructor に渡せない
directive 関数を呼び出すときに継承した新しいクラスを作って host プロパティにホスト要素を入れるようにする
更新の場合は Directive の constructor は呼び出されず render のみ呼び出される
一旦 DOM が削除されるような場合は再度作成されたときにまた Directive が作られる