Last active
September 21, 2019 05:48
-
-
Save ursi/f211369e4a773a08a345087abc0dfe28 to your computer and use it in GitHub Desktop.
a function for generating getters and setters for custom element classes
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
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); | |
} |
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
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