I am building a page with multiple timers on it. The timers are created when a user clicks a button. So let's say user clicks "K Timer 1" button. The JS created a new timer I want to reference as "KT1" or timers['KT1'].
Here is the way I am trying to do it and you JS peeps are probably laughing at my solution right now. That's OK. I am much more at home with PHP.
HTML
<button type="button"
onClick="newUTimer('KT1');">
Timer 1
</button>
<button type="button"
onClick="newUTimer('KT2');">
Timer 2
</button>
JS - Old with errors
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();
}
}
The reason I need to keep track of the timers is so that I can reset the timer when a user click button for the second time instead of creating another conflicting timer.
JS - UPDATED and Working but not sure this is the correct way I should do this.
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();
}
}
CodePudding user response:
Lose the dots before array brackets:
globalThis.timers.[id].starter()
should be globalThis.timers[id].starter()
CodePudding user response:
You should accept aPajos answer as it pointed out your actual error. As for the "more correct way", get rid of inline javascript
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>