Skip to content

Instantly share code, notes, and snippets.

@calebdwilliams
Created May 14, 2021 19:27
Show Gist options
  • Save calebdwilliams/a45ea13f6290e89fa8fcd3f4ae6278f7 to your computer and use it in GitHub Desktop.
Save calebdwilliams/a45ea13f6290e89fa8fcd3f4ae6278f7 to your computer and use it in GitHub Desktop.
Synt attributes and properties for custom elements
export function syncAttributesAndProperties(self) {
self.constructor.observedAttributes.forEach(attribute => {
const descriptor = Object.getOwnPropertyDescriptor(self.constructor.prototype, attribute);
Object.defineProperty(self, attribute, {
get() {
if (descriptor?.get) {
return descriptor.get.apply(self, []);;
}
return self.getAttribute(attribute);
},
set(_value) {
if (_value && self[attribute] !== _value) {
self.setAttribute(attribute, _value);
} else if (!_value) {
self.removeAttribute(attribute);
}
if (descriptor?.set) {
descriptor.set.apply(self, [_value]);
}
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment