Skip to content

Instantly share code, notes, and snippets.

@ursi
Last active September 21, 2019 05:48
Show Gist options
  • Save ursi/f211369e4a773a08a345087abc0dfe28 to your computer and use it in GitHub Desktop.
Save ursi/f211369e4a773a08a345087abc0dfe28 to your computer and use it in GitHub Desktop.
a function for generating getters and setters for custom element classes
function cgs(param) {
if (Array.isArray(param)) var [attr, defaultValue] = param;
else var attr = param;
const descriptor = {
set: function(value) {
this.setAttribute(attr, value);
},
configurable: true,
};
if (defaultValue) {
descriptor.get = function(){
return this.getAttribute(attr) || defaultValue;
}
} else {
descriptor.get = function(){
return this.getAttribute(attr);
}
}
Object.defineProperty(this.constructor.prototype, attr, descriptor);
}
function createGettersAndSetters(gs) {
let str = ``;
for (let name of gs) {
str += `get ${name}() {
return this.getAttribute(\`${name}\`);
}
set ${name}(value) {
this.setAttribute(\`${name}\`, value);
}
`
}
console.log(str.slice(0, -2));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment