实现说明
全部实现位于 UserBadge。
演示用的数据放在这几个模块级绑定中:badge。
使用要点
document只存在于浏览器——Node 运行时没有现成的垫片。- 演示输出是带标签的(
badge renders:),每个操作都会留下自己的一行标注。
常见问题
「Custom Elements 声明式监听属性变更」能在裸 Node.js 里跑吗?
不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。
核心语句
this.textContent = `${this.getAttribute('name') ?? 'anon'} · ${this.displayRole}`;
if (name === 'role') this.displayRole = next ?? 'guest';
代码示例
// Custom Elements: observedAttributes declares the config keys the component watches (its configuration surface),
// attributeChangedCallback reacts to each change
class UserBadge extends HTMLElement {
static observedAttributes = ['name', 'role'];
private displayRole = 'guest';
connectedCallback(): void {
this.render();
}
attributeChangedCallback(name: string, _oldValue: string | null, next: string | null): void {
if (name === 'role') this.displayRole = next ?? 'guest';
if (name === 'name') this.render();
}
private render(): void {
this.textContent = `${this.getAttribute('name') ?? 'anon'} · ${this.displayRole}`;
}
}
customElements.define('user-badge', UserBadge);
// Declaration merging makes querySelector/createElement('user-badge') return UserBadge directly
declare global {
interface HTMLElementTagNameMap {
'user-badge': UserBadge;
}
}
export {};
const badge = document.createElement('user-badge');
badge.setAttribute('name', 'Ada');
badge.setAttribute('role', 'admin');
document.body.append(badge);
console.log('badge renders:', badge.textContent);