DEV Community

loading...

Discussion on: Learn basic Web Components

Collapse
webpreneur profile image
Zsolt Gulyas

Truly said. Altough I wouldn't say just because of this, that the docs are "incorrect". Maybe the first one is more readable for newcomers. Anyway, super useful comment though. Thanks.

Collapse
dannyengelman profile image
Danny Engelman • Edited

See what code newcomers have to dig through (unless they don't RTFM) in the attachShadow MDN documentation: developer.mozilla.org/en-US/docs/W...

If you understand "// Always call super first in constructor" is incorrect
you can write that 33 lines constructor (most likely) without any comments:

constructor() {

  let span = document.createElement('span');

  function countWords() {
    let node = this.parentNode;
    let text = node.innerText || node.textContent;
    let count = text.trim().split(/\s+/g).length;
    span.innerText = 'Words: ' + count;
  }

  super()
   .attachShadow({mode: 'open'})
   .append( span );

  countWords();
  setInterval(()=> countWords() , 200);
}
Enter fullscreen mode Exit fullscreen mode

If you want to score W3C points; feel free to update that MDN article.

I did some MDN updates; then concluded there is way more effect adding comments to Web Component blogposts.
And I recently published my first Dev.to post explaining Web Components are about semantic HTML (IMHO)

And ... there is more wrong in that MDN Count Words example..

  • this.parentNode DOM access should be done in the connectedCallback, as the DOM might not even exist when the constructor runs

  • <p is="word-count"></p> Will never work in Safari, because Apple only implemented Autonomous Elements and (for the past 5 years) has strong arguments to not implement Customized Built-In Elements

Forem Open with the Forem app