Have you ever wondered why native web components have an API to handle attribute changes but not property changes?
This script implements both observedProperties
and propertyChangedCallback
that behave just like observedAttributes
and attributeChangedCallback
do.
In the background, it uses ES6 setters to cause a side-effect — run the callback method — everytime a property changes.
npm install observed-properties --save
Import withObservedProperties
.
import withObservedProperties from 'observed-properties';
Use the whole path to the index.js
file if you want the script to work on modern browsers natively, without having to depend on a build process.
import withObservedProperties from './node_modules/observed-properties/src/index.js';
Enhance the HTMLElement
by passing it to the withObservedProperties
helper.
const EnhancedHTMLElement = withObservedProperties(HTMLElement);
Create a new web component class that extends EnhancedHTMLElement
.
class TopTen extends EnhancedHTMLElement {}
Tell the component which properties to observe by setting observedProperties
.
class TopTen extends EnhancedHTMLElement {
static get observedProperties () {
return ['songs'];
}
}
Set propertyChangedCallback
, the method that will be run everytime a property changes.
class TopTen extends EnhancedHTMLElement {
static get observedProperties () {
return ['songs'];
}
propertyChangedCallback (propName, oldValue, value) {
if (propName === 'songs' && oldValue !== value) {
this.render(value);
}
}
}
import withObservedProperties from 'observed-properties';
const EnhancedHTMLElement = withObservedProperties(HTMLElement);
class TopTen extends EnhancedHTMLElement {
static get observedProperties () {
return ['songs'];
}
constructor () {
super();
this.attachShadow({ mode: 'open' });
}
propertyChangedCallback (propName, oldValue, value) {
if (propName === 'songs' && oldValue !== value) {
this.render(value);
}
}
render (value = []) {
this.shadowRoot.innerHTML = `
<dl>
${value.map(song => `
<dt>${song.name}</dt>
<dd>${song.artist} – ${song.year}</dd>
`).join('')}
</dl>
`;
}
}
window.customElements.define('top-ten', TopTen);
This script does not play along with Polymer, SkateJS and possibly other web component libraries. The reason is that they use the same approach to detect property changes and it causes conflicts.
Another possible approach would be to use ES6 Proxies, but they are known to have performance issues and, if you are using a web component library, then you probably already have a way to detect property changes.