Skip to content

Instantly share code, notes, and snippets.

@mig82
Last active June 9, 2021 08:30
Show Gist options
  • Save mig82/d965b538c640ef9422df7b0f60027584 to your computer and use it in GitHub Desktop.
Save mig82/d965b538c640ef9422df7b0f60027584 to your computer and use it in GitHub Desktop.
defineSetters and defineGetters
"use strict"
/*exported defineGetters*/
/**
* Applies a function as the getter function for all the custom properties
* of a component named in an array.
* This is useful to avoid repeating yourself when the getter for two or more
* custom properties is the same —e.g.
* <pre><code>
* defineGetters(this, ['foo','bar'], prop => { return this['_' + prop] })
* </code></pre>
*
* @param {Controller} ctrl - The controller of the component for which the custom properties are defined.
* @param {Array} props - The array of the properties for which the getter will be set.
* @param {Function} getter - The function that will be defined as the getter for the properties mentioned in the array.
*/
const defineGetters = (ctrl, props, getter) => {
props.forEach((prop/*, i, arr*/) => {
/*globals defineGetter*/
defineGetter(ctrl, prop, () => {
getter.call(ctrl, prop)
})
})
}
/*exported defineSetters*/
/**
* Applies a function as the setter function for all the custom properties
* of a component named in an array.
* This is useful to avoid repeating yourself when the setter for two or more
* custom properties is the same —e.g.
* <pre><code>
* defineSetters(this, ['foo','bar'], (value, prop) => { this['_' + prop] = value })
* </code></pre>
*
* @param {Controller} ctrl - The controller of the component for which the custom properties are defined.
* @param {Array} props - The array of the properties for which the setter will be set.
* @param {Function} setter - The function that will be defined as the setter for the properties mentioned in the array.
*/
const defineSetters = (ctrl, props, setter) => {
props.forEach((prop/*, i, arr*/) => {
/*global defineSetter*/
defineSetter(ctrl, prop, (value) => {
setter.call(ctrl, value, prop)
})
})
}
//Then, in a component, just define something like:
initGettersSetters: function() {
/*globals defineSetters defineGetters*/
const stringProps = ['foo', 'bar']
defineSetters(this, stringProps, (value, prop) => {
this['_' + prop] = value
})
const floatProps = ['qux', 'baz']
defineSetters(this, floatProps, (value, prop) => {
this['_' + prop] = parseFloat(value || 0)
})
const allProps = stringProps.concat(floatProps)
defineGetters(this, allProps, prop => {
return this['_' + prop]
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment