我需要一个由游戏逻辑组成的外部类,调用 LitElement 组件,并向其传递一个 html 模板文字,该组件将使用该文字来更新其自己的 html 模板文字的一部分。
在下面的代码中,您将看到组件的一个方法 (navigationRender
),可以从组件内部成功调用该方法。也可以从外部 game
类成功调用相同的方法(如 console.log 所示)。但是,即使可以调用它,它也没有成功更新组件的 html 模板。
navigationRender
是否需要某种回调到 firstUpdated
的范围内?我已经无法理解了,如果这就是需要的,那么我无论如何都不知道该怎么做......
下面是已压缩到单个文件中的代码。如果单击“更改描述”按钮,您将看到 console.log 使用传递的 html 模板进行更新,但看不到渲染的 html 文本。
<body>
<front-end></front-end>
</body>
<script type="module">
import { LitElement, html, css } from 'https://unpkg.com/lit-element?module';
class FrontEnd extends LitElement {
constructor() {
super();
this.renderDescription = html`<p>initialized - 01</p>`;
}
render() {
return [
html`<button id="btn">Change Description</button>`,
this.renderDescription];
}
firstUpdated() {
this.game = new Game();
this.navigationRender(html`<p>DESCRIPTION: So far, working when called from firstUpdated(). But what about when called from the Game class?</p>`);
this.shadowRoot.getElementById('btn').addEventListener('click', (e) => {
this.game.newDescription();
});
}
navigationRender(description) {
console.log(description);
this.renderDescription = description;
this.requestUpdate();
}
}
customElements.define('front-end', FrontEnd);
class Game {
constructor() {
this.frontEnd = new FrontEnd();
}
newDescription() {
this.frontEnd.navigationRender(html`DESCRIPTION: Although the console.log verifies that this.frontEnd.navigationRender is being called and the data passed, that function is not able to actually update the this.renderDescription when called from the game class.`);
}
}
</script>
感谢您的帮助和建议!
最佳答案
我明白了。希望这对其他人有帮助。
<body>
<front-end id="fe-id"></front-end>
</body>
<script type="module">
import { LitElement, html, css } from 'https://unpkg.com/lit-element?module';
class FrontEnd extends LitElement {
constructor() {
super();
this.renderDescription = html`<p>initialized - 01</p>`;
}
render() {
return [
html`<button id="btn">Change Description</button>`,
this.renderDescription];
}
firstUpdated() {
this.game = new Game();
this.navigationRender(html`<p>So far, working when called from firstUpdated(). But what about when called from the Game class?</p>`);
this.shadowRoot.getElementById('btn').addEventListener('click', (e) => {
this.game.newDescription();
});
}
navigationRender(description) {
console.log(description);
this.renderDescription = description;
this.requestUpdate();
}
}
customElements.define('front-end', FrontEnd);
class Game {
constructor() {
// this.frontEnd = new FrontEnd();
this.element = document.getElementById('fe-id');
}
newDescription() {
this.element.navigationRender(html`<p>YAY!! THIS WORKS!!!</p>`);
}
}
</script>
关于javascript - 外部类调用 LitElement 组件方法(传递 html 模板),组件方法更新其 html 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60895876/