0.0.7 • Published 4 years ago
plum-element v0.0.7
plum-element
A tiny base class for web components to sync between properties and attributes. ⚡️ No dependencies, less than 500 bytes gzipped.
Installation
yarn add plum-elementUsage
class ToDoElement extends PlumElement {
// Declare properties.
static get plProps(): PlumPropDefs {
return {
// Define a string property named 'description'.
description: 's',
// Define a boolean property named 'completed'.
completed: 'b',
};
}
// Description property getter and setter.
get description(): string {
return this.getPLProp('description');
}
set description(val: string) {
this.setPLProp('description', val);
}
// Completed property getter and setter.
get completed(): boolean {
return this.getPLProp('completed');
}
set completed(val: boolean) {
this.setPLProp('completed', val);
}
}
customElements.define('todo-element', ToDoElement);PlumElement properties and attributes are automatically in sync:
<todo-element id="element" description="Fix bugs" completed></todo-element>
<script>
const element = document.getElementById('element');
// Get initial attributes.
element.description; // 'Fix bugs'
element.completed; // true
// Property changes are reflected in attributes.
element.description = 'Create bugs';
element.getAttribute('description'); // Returns 'Create bugs'
// Attribute changes are also reflected in properties.
element.removeAttribute('completed');
element.completed; // Returns false
</script>Supported property types
sstring.nnumber.bboolean.falseremoves the attribute.aarray. JSON is used for serialization / deserialization.objectobject. JSON is used for serialization / deserialization.
NOTE: null or undefined property values always remove the attribute.
Property / attribute change callback
Whenever a property or attribute changes, these two functions are always called in pairs.
class MyElement extends PlumElement {
// Called when a property is updated.
// `attrToPropUpdate` true if this is triggered by an attribute change.
onPLPropUpdated(name: string, oldValue: unknown, newValue: unknown, attrToPropUpdate: boolean) {}
// Called when an attribute is updated.
// `attrToPropUpdate` true if this is triggered by an attribute change.
onPLAttributeUpdated(
name: string,
oldValue: string | null,
newValue: string | null,
attrToPropUpdate: boolean,
) {}
}Just like the standard attributeChangedCallback, these two functions are also called before an element is connected, use HTMLElement.isConnected if you are only interested in changes when an element is connected. Example:
class MyElement extends PlumElement {
connectedCallback() {
// Handle property values all at once in `connectedCallback`.
}
onPLPropUpdated(name: string, oldValue: unknown, newValue: unknown, attrToPropUpdate: boolean) {
// Ignore property changes when the element is not connected.
if (!this.isConnected) {
return;
}
// Handle property changes.
}
}