Tengo una clase Javascript estándar que crea un montón de HTML, esencialmente una colección de objetos HTMLElement relacionados que forman la interfaz de usuario para un componente y los agrega al documento HTML. La clase implementa la lógica del controlador, respondiendo a eventos, mutando algunos de los HTMLElements, etc.
Mi instinto (procedente de más experiencia en desarrollo de back-end) es almacenar esos objetos HTMLElement dentro de mi clase, ya sea dentro de un objeto clave/valor o en una matriz, para que mi clase pueda acceder a ellos directamente a través de propiedades nativas siempre que esté haciendo algo con ellos. . Pero todo lo que miro parece seguir el patrón de confiar en los selectores de documentos ( document.getElementById , getElementsByClassName , etc., etc.). Entiendo la utilidad general de ese enfoque, pero se siente extraño tener una clase que crea objetos, descarta sus propias referencias a ellos y luego los vuelve a buscar cuando es necesario.
Un ejemplo simplificado se vería así:
<html> <body> <script> /* Silly implementation of the "Concentration" memory match game. This is just a S/O example but it should actually work =P */ class SymbolMatchGame { constructor(symbolsArray) { this.symbols = symbolsArray.concat(symbolsArray); // we want two of every item this.allButtons = []; this.lastButtonClicked = null; } shuffle() { for (let i = this.symbols.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); const temp = this.symbols[i]; this.symbols[i] = this.symbols[j]; this.symbols[j] = temp; } } build(parentElement) { document.body.innerHTML = ''; this.shuffle(); const rowSize = Math.floor(Math.sqrt(this.symbols.length)); for (let i = 0; i < this.symbols.length; i++) { const button = document.createElement('input'); button.type = 'button'; button.setAttribute('secret-value', this.symbols[i]); button.value = ' '; button.onclick = (event) => this.turnOver(event); this.allButtons.push(button); document.body.appendChild(button); if ((i+1) % rowSize === 0) { const lineBreak = document.createElement('br'); document.body.appendChild(lineBreak); } } } turnOver(event) { const button = event.target; if (this.lastButtonClicked === null) { this.allButtons.forEach(button => button.value = button.disabled ? button.value : ' '); this.lastButtonClicked = button; } else if (button === this.lastButtonClicked) { button.value = ' '; this.lastButtonClicked = null; } else { if (button.getAttribute('secret-value') === this.lastButtonClicked.getAttribute('secret-value')) { console.log('Match found!'); button.disabled = true; this.lastButtonClicked.disabled = true; } else { console.log('No match!'); } this.lastButtonClicked = null; } button.value = button.getAttribute('secret-value'); if (this.gameIsSolved()) { alert('You did it! Game will reset.') this.build(); } } gameIsSolved() { const remainingButtons = game.allButtons.filter(button => !button.disabled) return remainingButtons.length === 0; } } const alphabetArray = Array.from(Array(8).keys()).map(k => String.fromCharCode(k+65)); game = new SymbolMatchGame(alphabetArray); game.build(); </script> </body> </html> (Nota: no espero que examine este código en detalle; solo ilustra lo que quiero decir cuando hablo de almacenar referencias de elementos en la clase y acceder a ellos directamente en lugar de mediante búsquedas document.get* )
No quiero que esta sea una pregunta de estilo/"mejores prácticas" que no sea apropiada para S/O, así que busco más información concreta sobre si mi enfoque realmente funciona de la manera que creo que lo hace. Mi pregunta: ¿cuáles son las implicaciones o efectos secundarios de lo que estoy haciendo? Está almacenando referencias a elementos creados dentro de mi clase en lugar de un document.get* búsqueda cada vez que quiero acceder o modificarlos inseguro de alguna manera, propenso a efectos secundarios o referencias obsoletas, o que carece de garantías implícitas sobre el estado del documento, ¿eso podría romperme las cosas?