Подключенный обратный вызов не вызывается при создании пользовательских элементов HTML - PullRequest
0 голосов
/ 11 октября 2019

Я пытался создать пользовательский тег в HTML, используя JavaScript. Я хочу создать пользовательский элемент, используя синтаксис 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>`;
};
<neo-element></neo-element>

Я убедился, что NeoElement правильно расширяет HTMLElement, но все равно ничего не печатается внутри тега <neo-element>.

Может ли кто-нибудь посмотретьв коде и скажите мне, что мне не хватает в синтаксисе ES5?

1 Ответ

0 голосов
/ 11 октября 2019

Это не работает, потому что вы звоните customElements.define - и тем самым обновляете ваш <neo-element> до экземпляра NeoElement - до того, как вы определили NeoElement.prototype, NeoElement.prototype.constructor и NeoElement.prototype.connectedCallback.

Если переместить 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);
<neo-element></neo-element>
...