lwc icon indicating copy to clipboard operation
lwc copied to clipboard

Components do not respect observedAttributes/attributeChangedCallback

Open nolanlawson opened this issue 1 year ago • 1 comments

Description

LWC components do not respect observedAttributes or attributeChangedCallback. attributeChangedCallback is never called.

Create an LWC component:

import { LightningElement, api } from 'lwc'

export default class extends LightningElement {
  static observedAttributes = ['foo']

  @api changes = []

  attributeChangedCallback(name, oldValue, newValue) {
    this.changes.push({ name, oldValue, newValue })
  }
}

The attributes are never observed:

const elm = createElement('x-observes', { is: Observes })
document.body.appendChild(elm)

elm.setAttribute('foo', 'bar')
elm.removeAttribute('foo')

// attributeChangedCallback never called
console.log(elm.changes) // []

Steps to Reproduce

Repro (look in the console)

Expected Results

Attributes are observed

Actual Results

Attributes are not observed

Possible Solution

Use properties and @track instead of attributes

nolanlawson avatar Aug 02 '22 17:08 nolanlawson

This issue has been linked to a new work item: W-11534181

git2gus[bot] avatar Aug 02 '22 17:08 git2gus[bot]

CustomElementConstructor seems to work similarly, but slightly differently:

  • static observedAttributes is ignored – only the @api props are considered
  • attributeChangedCallback is also ignored
  • However, the framework registers an attributeChangedCallback to decide when to set a prop:

https://github.com/salesforce/lwc/blob/acc19c692f57ed8405a10a09b77f174ea015e440/packages/%40lwc/engine-core/src/framework/base-bridge-element.ts#L84-L114

nolanlawson avatar May 16 '23 21:05 nolanlawson