refactor: make props read-only

This commit is contained in:
Ayo 2023-11-17 23:31:10 +01:00
parent 63175c6c9f
commit 2616591315
2 changed files with 12 additions and 6 deletions

View file

@ -93,7 +93,9 @@ This mental model attempts to reduce the cognitive complexity of authoring compo
## Prop Access
A `WebComponent.props` read-only property exists to provide easy access to *any* observed attribute. This works like [`HTMLElement.dataset`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset) except `dataset` is only for attributes prefixed with `data-*`. Assigning a value to a camelCase counterpart using `WebComponent.props` will call `this.setAttribute` for any attribute name, with or without the `data-*` prefix.
There is a `WebComponent.props` read-only property provided for easy access to *any* observed attribute. This works like [`HTMLElement.dataset`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset) except `dataset` is only for attributes prefixed with `data-*`.
A camelCase counterpart using `props` will give read/write access to any attribute, with or without the `data-*` prefix.
You can access attribute properties in two ways:
1. Use the camelCase counterpart: `this.props.myProp`, which is automatically filled.

View file

@ -43,9 +43,9 @@ export class WebComponent extends HTMLElement {
}
/**
* Proxy object containing camelCase counterparts of observed attributes.
* Read-only property containing camelCase counterparts of observed attributes.
* This works like HTMLElement.dataset except dataset is only for attributes prefixed with `data-`.
* Assigning a value to a camelCase counterpart using `props` will automatically call `this.setAttribute` under the hood for any attribute name, with or without the `data-` prefix.
* A camelCase counterpart using `WebComponent.props` will give read/write access to any attribute, with or without the `data-*` prefix.
* @see https://www.npmjs.com/package/web-component-base#prop-access
* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
*
@ -61,13 +61,17 @@ export class WebComponent extends HTMLElement {
* }
* }
*/
props;
get props() {
return this.#props;
}
#props;
constructor() {
super();
if (!this.props) {
if (!this.#props) {
const { props, ...clone } = this;
this.props = new Proxy(clone, this.#handler(this));
this.#props = new Proxy(clone, this.#handler(this));
}
}