I'm building an JS application where I'm using multiple timers (digital, analog). I would like to use a base class for the Timer
with the functions: start, stop, update, etc.
Every time there is a timer created there are also new onChange
event created. So when the timer ticks multiple instances get an update, not only the one where the timer is created in.
My question is: how can I bind and Timer
instance the another class?
Timer class:
class Timer = {
constructor() {
this.seconds = 0;
}
start() {
this.timer = setInterval(update, 25);
}
stop() {
clearInterval(this.timer);
}
update() {
this.seconds += 1;
//emit data
let event = new Event("timer-tick");
event.detail = {
seconds: seconds,
}
document.body.dispatchEvent(event);
}
}
DigitalTimer class:
class DigitalTimer = {
constructor() {
this.timer = new Timer();
this.handleEvent();
}
handleEvent() {
$('body').on('timer-tick', function(e) {
//tick, do somehting with it.
});
}
start() {
this.timer.start();
}
stop() {
this.timer.stop()
}
}