Issue
Looks like if a custom element is created before it's been defined, it will have the HTMLElement
constructor, and retain this even after the definition is completed.
Creating that element again will have the correct constructor, see code example below.
const comp = document.createElement("my-comp");
console.log('First element before definition: ', comp.constructor.name);
customElements.define("my-comp", class MyComp extends HTMLElement {
constructor() { super(); }
myMethod() { return; }
}
);
console.log('First element after definition: ', comp.constructor.name);
try { comp.myMethod() }
catch (e) { console.error(e) }
const secondComp = document.createElement("my-comp");
console.log('Second element: ', secondComp.constructor.name);
Solution
If you are sure you have now defined the component, you can use
!customElements.get(comp) && customElements.upgrade(comp)
to upgrade the component so that its constructor is changed to the custom element's class.
const comp = document.createElement("my-comp");
console.log('Component before definition: ', comp.constructor.name);
customElements.define("my-comp", class MyComp extends HTMLElement {
constructor() { super(); }
myMethod() { return; }
}
);
console.log('Component after definition: ', comp.constructor.name);
!customElements.get(comp) && customElements.upgrade(comp)
console.log('Component after upgrade: ', comp.constructor.name);
Answered By - David Min
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.