Estoy creando una página con varios temporizadores. Los temporizadores se crean cuando un usuario hace clic en un botón. Así que digamos que el usuario hace clic en el botón "K Timer 1". El JS creó un nuevo temporizador al que quiero hacer referencia como "KT1" o temporizadores ['KT1'].
Esta es la forma en que estoy tratando de hacerlo y ustedes, los JS, probablemente se estén riendo de mi solución en este momento. Está bien. Estoy mucho más en casa con PHP.
HTML
<button type="button" onClick="newUTimer('KT1');"> Timer 1 </button> <button type="button" onClick="newUTimer('KT2');"> Timer 2 </button>JS - Antiguo con errores
var timers = {}; newUTimer=function(id){ // If timer does not exist, create it if (!globalThis.timers.[id]){ globalThis.timers.[id] = new CUTimer(id); globalThis.timers.[id].starter(); // If there is already a timer with that ID, reset it }else{ globalThis.timers.[id].reset(); } }La razón por la que necesito realizar un seguimiento de los temporizadores es para poder restablecer el temporizador cuando un usuario hace clic en el botón por segunda vez en lugar de crear otro temporizador en conflicto.
JS: ACTUALIZADO y en funcionamiento, pero no estoy seguro de que esta sea la forma correcta en que debo hacerlo.
var timers = {}; newUTimer=function(id){ // If timer does not exist, create it if (!globalThis.timers[id]){ globalThis.timers[id] = new CUTimer(id); globalThis.timers[id].starter(); // If there is already a timer with that ID, reset it }else{ // Call object resetIt method globalThis.timers[id].resetIt(); } }Pierda los puntos antes de los corchetes de matriz: globalThis.timers.[id].starter() debe ser globalThis.timers[id].starter()
Debe aceptar la respuesta de aPajos , ya que señaló su error real. En cuanto a la "forma más correcta", deshágase de javascript en línea
var timers = {}; /*Get the buttons with the data attributes*/ let timerButtons = document.querySelectorAll("button[data-timerid]"); /*Itterate them adding an event handler*/ timerButtons.forEach(function(item){ item.addEventListener("click", function(){ /*Get the id from the data atttribute*/ let timerId = this.dataset.timerid; /*Better to go the positive case first*/ if(timers[timerId]){ timers[timerId].resetIt(); }else{ timers[timerId] = new CUTimer(timerId); } }); }) function CUTimer(id){ this.id = id; this.starter = function(){console.log("Starting : " + this.id)}; this.resetIt = function(){console.log("Resetting : " + this.id)}; //Call your starter method in the construtor this.starter(); }; <!-- Use Data Attributes to store the timer Id --> <button type="button" data-timerid='KT1'>Timer 1</button> <button type="button" data-timerid='KT2'>Timer 2</button>