【问题标题】:ELM Custom ElementsELM 自定义元素
【发布时间】:2019-10-10 12:53:15
【问题描述】:

我有以下 ELM 视图元素:

Html.node "test-elem" 
 [ Attributes.attribute "data-count" (model.count |> String.fromInt) ]
 []

test-elem 是一个自定义的 html 元素:

 constructor() {
        super();
        this.me = this;
    }
    connectedCallback() {
        console.info(this.dataset.count);
        this.div = document.createElement("div");
        this.appendChild(this.div);
        this.div.innerText = "" + this.dataset.count;
    }

   attributeChangedCallback() {
        console.info(this.dataset.count);

        this.div.innerText = "" + this.dataset.count;
    }

如果 model.count 发生更改,自定义元素不会重新生成。我该如何强制?

https://ellie-app.com/6SRrZjCzwfra1

根据@Robin 的建议进行了编辑,但没有运气。

【问题讨论】:

    标签: elm custom-element


    【解决方案1】:

    我认为您的 Elm 代码没有任何问题,我认为这是您在 JavaScript 中自定义元素定义的问题。

    我不熟悉自定义元素 API,但查看您的代码(转载如下):

    customElements.define('test-elem', class TestElem extends HTMLElement {
    
            constructor() {
                super();
                this.me = this;
            }
            connectedCallback() {
                console.info(this.dataset.count);
                var div = document.createElement("div");
                this.appendChild(div);
                div.innerText = "" + this.dataset.count;
            }
        });
    

    MDN documentation for custom elements,显然你应该将connectedCallback 方法更改为attributeChangedCallback。原因是 Elm 使用虚拟 DOM 并在模型更改时使实际 DOM 更新最少。特别是,当计数发生变化时,它不会从 DOM 中删除自定义元素并添加一个新元素,它只会更改适当的属性。因此,您的connecedCallback 似乎不会被调用,但attributeChangedCallback 应该会。

    另外,正如@Murdock 正确观察到的(通过阅读 MDN 文章,特别是“使用生命周期回调”部分,比我更好),data-count 属性必须明确设置为观察,通过使用 @ 987654328@getter,如下:

    static get observedAttributes() {
        return ['data-count'];
    }     
    

    【讨论】:

    • 啊哇。好的,我已经更新了我的代码,但我仍然没有得到正确的行为。
    • 它永远不会命中attributeChangedCallback
    • 哦,好吧,我无法测试它,但很确定这会起作用。不知道还有什么建议。
    • 添加observedAttributes 解决了我的问题。静态获取observedAttributes() { return ['data-count']; }
    • 谢谢,很好地解决了这个问题。我已经编辑了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多