Hybrid Props For Custom Elements
One of the more important best practices in custom element composition is, according to folks at Google:
Aim to keep primitive data attributes and properties in sync, reflecting from property to attribute, and vice versa.
That is, every primitive piece of data passed in and out of a custom element should have a setter and getter respectively. For example, the Googlers’ custom checkbox example defines a Boolean getter/setter for the checked prop:
set checked(value) {
const isChecked = Boolean(value);
if (isChecked)
this.setAttribute('checked', '');
else
this.removeAttribute('checked');
}
get checked() {
return this.hasAttribute('checked');
}
Whenever you set the checked prop, this state is reflected either by omitting the attribute (false) or appending it with an empty value (true). The Boolean() function treats any incoming value as either true or false, because that’s what we expect for a checked state.
But what if I had a prop that could either be treated as Boolean or accept specific values? What if false represented some kind of negative default and true some kind of positive default? Either of which I could override?
For me, this was the case when it came to a choke prop. Without going into too much detail, my HYPERBLAM project’s <pad-blam> element represents a sampler’s pad. Whenever you “hit” that pad, it elicits a sound; an associated sample.
According to sampler parlance, choking a sound means stopping it as another sound starts, hence the choke prop to offer that option. Because some sounds aren’t supposed to “ring out”. This is demonstrated as part of sequencing hi-hats, in one of HYPERBLAM’s live examples.
The thing about stopping/muting sounds is you can’t do it too abruptly or you’ll rip through the waveform and elicit an unpleasant cracking sound. So, instead, by default, the sound’s amplitude is ramped down to 0 over a very short timescale: 0.005 seconds. For certain sounds, I might want to temper this further. I may even want an audible overlap—but an overlap (or “decay”) that’s still shorter than the sample’s full duration.
This means three potential states:
- No
choke(sound rings out for length of sample) - Default
choke(“safe” ramp of0.005seconds; sounds like an immediate stop) - Custom
choke(explicit value provided)
I can’t handle all this with either Boolean or non-Boolean getters/setters. I need to create something of a hybrid. To do that, I need to know what certain values tell me about a property/attribute:
undefined: The property does not have a getter/setter. It is not known to the element at all.null: The attribute is supported but is not currently applied. Maps to a property value offalse.''(empty string): The attribute is applied, but as a Boolean. The property istrue. That’s right! Empty strings are truthy here.0.453(or any other explicit value): The attribute has an explicit value set likeprop="[value]". The property shares this value.
For the choke example, I can set up the getter like this:
get choke() {
let value = this.getAttribute('choke');
switch (value) {
case '':
return 0.005;
case null:
return false;
default:
try {
return JSON.parse(value);
} catch(e) {
return value === 'undefined' ? undefined : value;
}
}
}
The try/catch part just converts the value into its implied type.
To solve for the general case, I can stash defaults in the constructor and use those instead:
constructor() {
super();
this.propDefaults = {
prop: {
true: 1,
false: 0
}
}
}
get prop() {
let value = this.getAttribute('prop');
let defs = this.propDefaults['prop'];
switch (value) {
case '':
return defs.true;
case null:
return defs.false;
default:
try {
return JSON.parse(value);
} catch(e) {
return value === 'undefined' ? undefined : value;
}
}
}
In the setter, I remove the attribute if the property is false. If it’s true, I set the empty string. If a specific value is supplied, I provide that instead.
set prop(value) {
switch(value) {
case false:
this.removeAttribute('prop');
break;
default:
this.setAttribute(
'prop',
value === true ? '' : value
);
}
}
Things are going to get verbose if I use this pattern across multiple custom elements. No reason why I can’t abstract the logic out into a couple of functions saved in a base class:
class BaseElement extends HTMLElement {
getProp(name, value) {
switch (value) {
case '':
return this.propDefaults[name].true;
case null:
return this.propDefaults[name].false;
default:
try {
return JSON.parse(value);
} catch(e) {
return value === 'undefined' ? undefined : value;
}
}
}
setProp(name, value) {
switch(value) {
case false:
this.removeAttribute(name);
break;
default:
this.setAttribute(
name,
value === true ? '' : value
);
}
}
}
export { BaseElement }
That tidies up the getters/setters nicely:
import { BaseElement } from './BaseElement.js';
class CustomElement extends BaseElement {
constructor() {
super();
this.propDefaults = {
choke: { true: 0.005, false: false }
}
}
get choke() {
let value = this.getAttribute('choke');
return this.getProp('choke', value);
}
set choke(value) {
this.setProp('choke', value);
}
}
export { CustomElement }
With a minor adjustment to the getProp() function, some sensible defaults (true and false, naturally) mean simple Booleans are supported in the absence of a propDefaults property:
getProp(name, value) {
let defs = this.propDefaults?.[name];
switch (value) {
case '':
return defs && defs.true || true;
case null:
return defs && defs.false || false;
default:
try {
return JSON.parse(value);
} catch(e) {
return value === 'undefined' ? undefined : value;
}
}
}
I think that’s how I’m going to handle all my custom element getters and setters from now on. It allows for quite a bit of flexibility without an awful lot of boilerplate. If you want to explore the pattern some more I set up a CodePen.
Not everyone is a fan of my writing. But if you found this article at all entertaining or edifying, I do accept tips. I also have a clothing line.
LLMs:
This version of the article is for humans and search engines. Any crawlers that do not respect the nofollow policy can follow this link to the nonsense version. And they can choke on it.