admin 管理员组文章数量: 1086019
I have been using Web Components for quite some time but now and then I keep running into some issues that I can't explain.
Some context:
- Attributes are used to pass text variables into a web component.
- Properties can be used to pass complex variables into a web component.
- A web component has a lifecycle method called ConnectedCallBack() that is called when our element gets added to the DOM.
What I am trying to do:
- I created two web components: parent-element and child-element
- Both have a property that you can use to pass in an object holding a text property that I want to display on screen; for these properties, I created a getter and setter method.
- Each component has a render() method responsible for creating some new HTML elements holding the property value and adding them to the DOM; these methods only produce output if the property is set.
I added some example code to demonstrate this. Mind the output that is generated in the browser but also the console log demonstrating the order in which the various methods are called on both components.
Please run the code snippets in "Full page" as you might not see the full browser output when you run them inline.
<html>
<head></head>
<body>
<app id="app"></app>
<script>
customElements.define('parent-element', class extends HTMLElement {
set parentProperty(value) {
console.log('PARENT: SET PROPERTY');
this._parentProperty = value;
this.render();
}
get parentProperty() {
return this._parentProperty;
}
constructor() {
super();
console.log('parent: constructor');
}
connectedCallback() {
console.log('parent: connectedCallback');
this.render();
}
render() {
console.log(`parent: render ${(this.parentProperty ? 'with' : 'no')} property`);
if (this.parentProperty) {
let templateEl = document.createElement("template");
templateEl.innerHTML = `<p>${this.parentProperty.value}</p><child-element id="child"></child-element>`;
this.appendChild(templateEl.content.cloneNode(true));
let childEl = this.querySelector('#child');
childEl.childProperty = { value: 'child text' };
}
}
});
customElements.define('child-element', class extends HTMLElement {
set childProperty(value) {
console.log('CHILD: SET PROPERTY');
this._childProperty = value;
this.render();
}
get childProperty() {
return this._childProperty;
}
constructor() {
super();
console.log('child: constructor');
}
connectedCallback() {
console.log('child: connectedCallback');
this.render();
}
render() {
console.log(`child: render ${(this.childProperty ? 'with' : 'no')} property`);
if (this.childProperty) {
let templateEl = document.createElement("template");
templateEl.innerHTML = `<p>${this.childProperty.value}</p>`;
this.appendChild(templateEl.content.cloneNode(true));
}
}
});
let appEl = document.querySelector('#app');
let parentEl = document.createElement('parent-element');
appEl.appendChild(parentEl);
parentEl.parentProperty = { value: 'parent text' };
</script>
</body>
</html>
I have been using Web Components for quite some time but now and then I keep running into some issues that I can't explain.
Some context:
- Attributes are used to pass text variables into a web component.
- Properties can be used to pass complex variables into a web component.
- A web component has a lifecycle method called ConnectedCallBack() that is called when our element gets added to the DOM.
What I am trying to do:
- I created two web components: parent-element and child-element
- Both have a property that you can use to pass in an object holding a text property that I want to display on screen; for these properties, I created a getter and setter method.
- Each component has a render() method responsible for creating some new HTML elements holding the property value and adding them to the DOM; these methods only produce output if the property is set.
I added some example code to demonstrate this. Mind the output that is generated in the browser but also the console log demonstrating the order in which the various methods are called on both components.
Please run the code snippets in "Full page" as you might not see the full browser output when you run them inline.
<html>
<head></head>
<body>
<app id="app"></app>
<script>
customElements.define('parent-element', class extends HTMLElement {
set parentProperty(value) {
console.log('PARENT: SET PROPERTY');
this._parentProperty = value;
this.render();
}
get parentProperty() {
return this._parentProperty;
}
constructor() {
super();
console.log('parent: constructor');
}
connectedCallback() {
console.log('parent: connectedCallback');
this.render();
}
render() {
console.log(`parent: render ${(this.parentProperty ? 'with' : 'no')} property`);
if (this.parentProperty) {
let templateEl = document.createElement("template");
templateEl.innerHTML = `<p>${this.parentProperty.value}</p><child-element id="child"></child-element>`;
this.appendChild(templateEl.content.cloneNode(true));
let childEl = this.querySelector('#child');
childEl.childProperty = { value: 'child text' };
}
}
});
customElements.define('child-element', class extends HTMLElement {
set childProperty(value) {
console.log('CHILD: SET PROPERTY');
this._childProperty = value;
this.render();
}
get childProperty() {
return this._childProperty;
}
constructor() {
super();
console.log('child: constructor');
}
connectedCallback() {
console.log('child: connectedCallback');
this.render();
}
render() {
console.log(`child: render ${(this.childProperty ? 'with' : 'no')} property`);
if (this.childProperty) {
let templateEl = document.createElement("template");
templateEl.innerHTML = `<p>${this.childProperty.value}</p>`;
this.appendChild(templateEl.content.cloneNode(true));
}
}
});
let appEl = document.querySelector('#app');
let parentEl = document.createElement('parent-element');
appEl.appendChild(parentEl);
parentEl.parentProperty = { value: 'parent text' };
</script>
</body>
</html>
Please focus on the part at the end:
let parentEl = document.createElement('parent-element'); -- I create an instance of my parent-element
appEl.appendChild(parentEl); -- I add it to the DOM by calling the appendChild() method
parentEl.parentProperty = { value: 'parent text' }; -- I set the property using an object
The browser output looks like this:
parent text
child text
And my console log looks like this:
parent: constructor
parent: connnectedCallback
parent: render no property
PARENT: SET PROPERTY
parent: render with property
child: constructor
child: connnectedCallback
child: render no property
CHILD: SET PROPERTY
child: render with property
Notice that when calling the appendChild() method, the respective connectedCallback() method is triggered which in turn calls the render() method; as the property hasn't been set yet, no output is produced.
After I set the property, the property setter is triggered which in turn calls the render() method again; as the property has now been set, actual output is generated.
So far, so good.
Now lets see what happens when I set the property on the parent element before adding it to the DOM.
<html>
<head></head>
<body>
<app id="app"></app>
<script>
customElements.define('parent-element', class extends HTMLElement {
set parentProperty(value) {
console.log('PARENT: SET PROPERTY');
this._parentProperty = value;
this.render();
}
get parentProperty() {
return this._parentProperty;
}
constructor() {
super();
console.log('parent: constructor');
}
connectedCallback() {
console.log('parent: connectedCallback');
this.render();
}
render() {
console.log(`parent: render ${(this.parentProperty ? 'with' : 'no')} property`);
if (this.parentProperty) {
let templateEl = document.createElement("template");
templateEl.innerHTML = `<p>${this.parentProperty.value}</p><child-element id="child"></child-element>`;
this.appendChild(templateEl.content.cloneNode(true));
let childEl = this.querySelector('#child');
childEl.childProperty = { value: 'child text' };
}
}
});
customElements.define('child-element', class extends HTMLElement {
set childProperty(value) {
console.log('CHILD: SET PROPERTY');
this._childProperty = value;
this.render();
}
get childProperty() {
return this._childProperty;
}
constructor() {
super();
console.log('child: constructor');
}
connectedCallback() {
console.log('child: connectedCallback');
this.render();
}
render() {
console.log(`child: render ${(this.childProperty ? 'with' : 'no')} property`);
if (this.childProperty) {
let templateEl = document.createElement("template");
templateEl.innerHTML = `<p>${this.childProperty.value}</p>`;
this.appendChild(templateEl.content.cloneNode(true));
}
}
});
let appEl = document.querySelector('#app');
let parentEl = document.createElement('parent-element');
parentEl.parentProperty = { value: 'parent text' };
appEl.appendChild(parentEl);
</script>
</body>
</html>
So all I did was swap these lines:
parentEl.parentProperty = { value: 'parent text' }; -- I set the property using an object
appEl.appendChild(parentEl); -- I add it to the DOM by calling the appendChild() method
Now, my browser output looks like this:
parent text
child text
parent text
And my console output looks like this:
parent: constructor
PARENT: SET PROPERTY
parent: render with property
parent: connectedCallback
parent: render with property
child: constructor
child: connectedCallback
child: render no property
child: constructor
child: connectedCallback
child: render with property
It looks like the parent element has been rendered twice as the property on the parent element was available on both calls to the render method.
So finally, after all of this, my questions:
- Why does the second rendering of the child element contain no text ?
- How can the first rendering of the child element contain text when the setter of the property on the child element has NOT been called ("CHILD: SET PROPERTY" is missing from the console output) ?
- As a rule of thumb, should I always call appendChild() before setting my properties on a web component ?
- What is the correct time to call the render() method ? On connectedCallback, in the property setter or on both like I do now ?
So grateful for your feedback.
Share Improve this question asked Mar 27 at 16:29 TomOdulTomOdul 1 3 |1 Answer
Reset to default 0Based on the remarks added, some help from my colleagues and a lot of research, I'm gonna try to answer my own question:
The child element is added twice and the querySelector is only returning the first one, so the text is modified twice in the first child element.
As long as appendChild is not called, the element is not part of the document model (DOM) and the custom element is not "upgraded" to an instance of the ChildElement class. Also, it's child custom element is not "upgraded" as long as the parent element is not connected and thus cannot be treated as such i.e. the property setter method will not be called when you set the child property.
Yes, you should call appendChild on the parent element before you start working with it to avoid the forementioned issues. As a workaround, you could call the customElements.upgrade() method on the child element before you set its properties. This method will upgrade all custom elements in a Node subtree, even before they are connected to the main document.
If you follow the suggestions in 2. and 3. it does not matter.
I created a test component with some configuration parameters at the top. You can play with these and inspect the browser console to see what is actually happening.
<html>
<head></head>
<body>
<script>
const setParentPropertyBeforeConnected = true;
const upgradeChildWhenNecessary = true;
const renderOnConnectedCallback = true;
class ChildElement extends HTMLElement {
set childProperty(value) {
console.log('*** CHILD: SET PROPERTY ***');
this._childProperty = value;
this.render();
}
get childProperty() { return this._childProperty; }
constructor() {
super();
console.log('child: constructor');
}
connectedCallback() {
console.log('child: connectedCallback');
if (renderOnConnectedCallback) this.render();
}
render() {
console.log(` => child: render - ${(this.childProperty ? 'property set' : 'property NOT set')} - ${this.isConnected ? 'connected' : 'NOT connected'}`);
if (this.childProperty) {
while (this.firstChild) this.removeChild(this.lastChild);
let templateEl = document.createElement("template");
templateEl.innerHTML = `<p>${this.childProperty.value}</p>`;
this.appendChild(templateEl.content.cloneNode(true));
}
}
}
customElements.define("child-element", ChildElement);
class ParentElement extends HTMLElement {
set parentProperty(value) {
console.log('parent: set property');
this._parentProperty = value;
this.render();
}
get parentProperty() { return this._parentProperty; }
constructor() {
super();
console.log('parent: constructor');
}
connectedCallback() {
console.log('parent: connectedCallback');
if (renderOnConnectedCallback) this.render();
}
render() {
console.log(` => parent: render - ${(this.parentProperty ? 'property set' : 'property NOT set')} - ${this.isConnected ? 'connected' : 'NOT connected'}`);
if (this.parentProperty) {
while (this.firstChild) this.removeChild(this.lastChild);
let templateEl = document.createElement("template");
templateEl.innerHTML = `<p>${this.parentProperty.value}</p><child-element id="child"></child-element>`;
console.log(` => parent: append child while ${this.isConnected ? 'connected' : 'NOT connected'}`);
this.appendChild(templateEl.content.cloneNode(true));
let childEl = this.querySelector('#child');
console.log(` => child: ${childEl instanceof ChildElement ? 'typed' : 'NOT typed'} - ${childEl.isConnected ? 'connected' : 'NOT connected'}`);
if (!(childEl instanceof ChildElement) && upgradeChildWhenNecessary) {
console.log(' => child: UPGRADE REQUIRED');
customElements.upgrade(childEl);
console.log(` => child: ${childEl instanceof ChildElement ? 'typed' : 'NOT typed'} - ${childEl.isConnected ? 'connected' : 'NOT connected'}`);
}
childEl.childProperty = { value: 'child text' };
}
}
}
customElements.define("parent-element", ParentElement);
let parentEl = document.createElement('parent-element');
if (setParentPropertyBeforeConnected) parentEl.parentProperty = { value: 'parent text' };
console.log('================== APPENDCHILD ==================');
debugger;
document.body.appendChild(parentEl);
if (!setParentPropertyBeforeConnected) parentEl.parentProperty = { value: 'parent text' };
</script>
</body>
</html>
Useful resources:
- https://html.spec.whatwg./multipage/custom-elements.html
- https://developer.mozilla./en-US/docs/Web/API/CustomElementRegistry/upgrade
本文标签: javascriptWeb Components set properties before or after ConnectedCallBackStack Overflow
版权声明:本文标题:javascript - Web Components: set properties before or after ConnectedCallBack - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744079872a2530035.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
createElement
was used, note thatcreateElement
triggers theconstructor
); but you can not add DOM content (unless its shadowDOM) when the Web Component isn't in the DOM yet.isConnected
tells you when you can: developer.mozilla./en-US/docs/Web/API/Node/isConnected Working more OOP will help. Try to create a BaseClass with shared functionality and have your parent and child elements doextend BaseClass
(this.nodeName or this.localName will always return your elements name) – Danny '365CSI' Engelman Commented Mar 27 at 16:52connectedCallback
does; see the deep-dive: dev.to/dannyengelman/… – Danny '365CSI' Engelman Commented Mar 27 at 16:55template
andcloneNode
. You can set HTML immediatly withthis.innerHTML = "..."
– Danny '365CSI' Engelman Commented Mar 27 at 16:58