【问题标题】:Connected callback is not being called while creating custom html elements创建自定义 html 元素时未调用连接的回调
【发布时间】:2020-02-09 09:00:15
【问题描述】:

我尝试使用 JavaScript 在 HTML 中创建自定义标签。我想使用 ES6 JavaScript 语法创建自定义元素。我编写了这段代码来创建自定义元素:

customElements.define('neo-element', NeoElement);
function NeoElement (){
    var ref =  Reflect.construct(HTMLElement,[], this.constructor) ;
    return ref;
};
NeoElement.prototype = Object.create(HTMLElement.prototype);
NeoElement.prototype.constructor = NeoElement;
NeoElement.prototype.connectedCallback = function(){
    this.innerHTML = `<h1>Hello world</h1>`;
};
&lt;neo-element&gt;&lt;/neo-element&gt;

我已经验证 NeoElement 正在正确扩展 HTMLElement,但在 &lt;neo-element&gt; 标记内仍然没有打印任何内容。

谁能看看代码并告诉我 ES5 语法中缺少什么?

【问题讨论】:

    标签: javascript html css ecmascript-6 ecmascript-5


    【解决方案1】:

    在您定义 NeoElement.prototypeNeoElement.prototype.constructorNeoElement.prototype.connectedCallback 之前,它不起作用,因为您正在调用 customElements.define,从而将您的 &lt;neo-element&gt; 升级为 NeoElement 的实例。

    如果您将customElements.define 移动到最后,它可以正常工作:

    function NeoElement() {
        var ref = Reflect.construct(HTMLElement,[], this.constructor) ;
        return ref;
    };
    NeoElement.prototype = Object.create(HTMLElement.prototype);
    NeoElement.prototype.constructor = NeoElement;
    NeoElement.prototype.connectedCallback = function(){
        this.innerHTML = `<h1>Hello world</h1>`;
    };
    customElements.define('neo-element', NeoElement);
    &lt;neo-element&gt;&lt;/neo-element&gt;

    【讨论】:

    • 谢谢。我在最后移动customElements.define('neo-element', NeoElement) 时工作。我认为当我们用原型定义任何东西时,这个顺序并不重要。但在这里,它打破了流程。
    • @NPrafull 在 JavaScript 函数声明中(即function someFn() { ... })是hoisted,但属性分配(someFn.myProp = ...)不是。分配给prototype 在这方面并不特别——它只是一个常规的属性分配——所以直到customElements.define 之后才发生。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 2013-06-23
    • 2014-03-21
    • 2020-11-28
    相关资源
    最近更新 更多