Created
May 14, 2021 19:27
-
-
Save calebdwilliams/a45ea13f6290e89fa8fcd3f4ae6278f7 to your computer and use it in GitHub Desktop.
Synt attributes and properties for custom elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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