DEV Community

Discussion on: Web Components: from zero to hero

Collapse
 
rafaferiah profile image
Rafa Romero Dios

Hi @pascal ! First of all thank you for the tutorial, is by far the best web-components tutorial I've faced to!

I have some doubts that I would like to solve :)

In the section Events I don't understand why do you handle the index as attribute instead of property:

// the way you do
set index(val) {
    this.setAttribute('index', val);
}
// the way I though it should be
set index(val) {
    this._index = val;
}

Also in this section, you refer to this.index instead of this._index:

this.dispatchEvent(new CustomEvent('onRemove', { detail: this.index }));

Is it OK or is it a mistake?

And the last one. In the section Reflecting properties to attributes I have the same problem with setters that I had with index. Why do you handle the checked as attribute instead of property??

// the way you do
get checked() {
    return this.hasAttribute('checked');
}

set checked(val) {
    if (val) {
        this.setAttribute('checked', '');
    } else {
        this.removeAttribute('checked');
    }
}

// the way I though it should be
get checked() {
    return this._checked;
}

set checked(val) {
    this._checked = val === true;
}

Many thanks in advance and congrats for your work!

Collapse
 
thepassle profile image
Pascal Schilp

Hi Rafa, this is mostly because attribution/property syncing. Arguably the index property doesn't need to be an attribute, but it's a good showcase on how to sync attributes with properties, and how to deal with different types than Strings.

If you'd set set index(val) { this._index = val }, the attribute won't be up to date with the property. When getting the index property, we can just read the attribute's value.

Same goes for the checked property, you'll almost definitely want the attribute to stay in sync with property, and its a showcase on how to handle boolean attributes as well.

Hope that clarifies — feel free to let me know if you have any more questions 😊

Collapse
 
rafaferiah profile image
Rafa Romero Dios • Edited

Hi Pascal! Thanks for your quick answer!

I understand what you say, but I thought that it was necessary to maintain a "model" (based on properties) that is mapped to all the attributes. That's why I thought that all the getters and setter should point to properties, instead of attributes.

Would it be possible to do it that way? I mean, maintain a model (properties based) and at the same time maintain up to date the syncronization between attributes and properties?

In the other hand, I understand then that attribute-properties mapped is not always mandatory, depending or you component logic, right?