Tengo un interruptor que necesita para agregar o eliminar clases. En mi archivo .ts tengo:
export default class extends Controller { static targets = [ "InformationOne", "InformationTwo", "InformationThree", "InformationFour", "InformationSwitchOne", "InformationSwitchTwo" ]; private InformationOne: HTMLElement[]; private InformationTwo: HTMLElement[]; private InformationThree: HTMLElement[]; private InformationFour: HTMLElement[]; private InformationSwitchOne: HTMLInputElement; private InformationSwitchTwo: HTMLInputElement; switchInformation(): void { if (this.InformationSwitchOne.checked) { this.InformationOne.forEach((item) => { item.classList.remove("d-none"); }); this.InformationTwo.forEach((item) => { item.classList.add("d-none"); }); this.InformationThree.forEach((item) => { item.classList.add("d-none"); }); this.InformationFour.forEach((item) => { item.classList.add("d-none"); }); } else if (this.InformationSwitchTwo.checked) { this.InformationTwo.forEach((item) => { item.classList.remove("d-none"); }); this.InformationOne.forEach((item) => { item.classList.add("d-none"); }); this.InformationThree.forEach((item) => { item.classList.add("d-none"); }); this.InformationFour.forEach((item) => { item.classList.add("d-none"); }); } } } Ahora la pregunta es, ¿cómo hacer que las líneas debajo sean más elegantes? ¿Hay alguna manera de tomar estos tres elementos y actuar sobre ellos classList.add en lugar de obtenerlos uno por uno?
this.InformationTwo.forEach((item) => { item.classList.add("d-none"); }); this.InformationThree.forEach((item) => { item.classList.add("d-none"); }); this.InformationFour.forEach((item) => { item.classList.add("d-none"); })Esto se puede simplificar:
this.InformationTwo .forEach((item) => { item.classList.add("d-none"); }); this.InformationThree.forEach((item) => { item.classList.add("d-none"); }); this.InformationFour .forEach((item) => { item.classList.add("d-none"); })...a esto:
const all = this.InformationTwo.concat( this.InformationThree ).concat( this.InformationFour ); for( const inp of all ) { inp.classList.toggle( 'd-none', /*force:*/ this.InformationSwitchOne.checked ); }Como describió en su último comentario, básicamente tiene un mapeo de listas y conmutadores y desea mostrar los elementos para cada conmutador, ¿correcto?
Entonces puedes hacer algo como esto:
switchInformation(): void { // a mapping which items are shown for which switch const mapping = [ // [HTMLInputElement, HTMLElement[]] [this.InformationSwitchOne, this.InformationOne], [this.InformationSwitchTwo, this.InformationTwo], [this.InformationSwitchThree, this.InformationThree], [this.InformationSwitchFour, this.InformationFour], ]; for (const [{ checked }, items] of mapping) { for (const item of items) { // toggle "d-none" based on wether the switch is checked or not. item.classList.toggle("d-none", !checked); } } }Y si el mapeo no cambia, incluso puede sacarlo de la función.