Member-only story
Reusable Web Components Notes
Notes and perspectives from native developer
This is a poorly organized article with notes about web development. There is no well developed narrative or thread, but I am putting it here in case others find useful information.
This is simply an artifact of my journey towards developing a better understanding of GUI programming on the Web. My background is as a developer using native toolkits such as Cocoa, WinForms, Gtk and Qt.
My understanding is that CSS frameworks such as Bootstrap dominate in making GUI apps today. However the more modern Reusable Web Components allows development of GUI applications on the web in a fashion which is more familiar to a native GUI toolkit developer such as myself.
Googler Eric Bidelman, has a great overview of how this works here, so I will not try to repeat everything he says.
Instead I will try to point out some of my own stumbling blocks in trying to understand this stuff.
The Wrong Way And Why It Is Wrong
There naive way to do this if you have not reflected up on how this should work is to create a new reusable web component like this:
class Foobar extends HTMLElement {
constructor() {
super();
this.innerHTML = '<p>hello</p>'
}
}
// Foobar becomes a custom HTML tag named <foo-bar>
// Name must have a hyphen (-), or it is illegal
customElements.define('foo-bar', Foobar);
This does not work, because you cannot modify visible DOM nodes before a node has been attached the DOM tree of the Web browser window. Think of this a bit like trying to wire up a controller in Cocoa, before the .nib
file has been loaded.
The Right Way
Instead we need to wait with modifying the DOM until our Node
object has been attached to the DOM. The connectedCallback
calls us to let us know that. So we write this instead:
class Foobar extends HTMLElement {
// called when node attached to a parent Node
connectedCallback() {
this.innerHTML = '<p>hello</p>'
}
}
customElements.define('foo-bar', Foobar);
Alternatively we can create our GUI in the Shadow DOM. The Shadow DOM is not shown in the regular DOM accessible from your web tools. The benefit of using it is that you can encapsulate class names, IDs and styles…