user2399646
user2399646

Reputation:

How to detect data property on web component set or altered

HTML:

<comp-two></comp-two>

JS:

class CompTwo extends HTMLElement {
    constructor() {
        super()
        this._options=[]
    }
    get options() {
        return this._options
    }
    set options(val) {
        this._options = val
    }
}

const el = document.querySelector('comp-two')
el.options = ['one','two','three']

Is there an accepted method for notifying the code inside the webComponent that a property has been set? If it makes any difference I'm nesting web components.

I can see that setting an attribute would do it, but seems wasteful?

Upvotes: 1

Views: 2517

Answers (1)

user2399646
user2399646

Reputation:

A property can be read directly:

console.log(this.propertyName)

But as the value could change any time after the component is created, the problem is to know when a change occurs, similar to how attributeChangedCallback is used to act on attribute updates.

A setter will trigger when the named property is written to. Just like attributeChangedCallback for attributes, the property's value has not necessarily changed.

set propertyName(val){
    this._propertyName = val // keep a copy, name must be different
                             // underscore is popular method
    this.doSomething(val)    // act on the new property value
}

get propertyName(){
    return this._propertyName
}

Note: After including a setter the property can no longer be read directly. Use a getter to return the local copy saved by the setter, or just read the local copy directly.

The penny finally dropped for me..

Upvotes: 1

Related Questions