JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Simple setInterval clock</title>
<style>
p {
font-family: sans-serif;
}
</style>
</head>
<body>
<div id="root"></div>
</body>
</html>
JavaScript
class TimerView {
startListeners = [];
stopListeners = [];
resetListeners = [];
constructor() {
this.rootElement = document.createElement('div');
this.rootElement.classList.add('timer');
this.startButton = document.createElement('button');
this.startButton.classList.add('timer__start-button');
this.startButton.textContent = 'Start';
this.startButton.addEventListener('click', () => {
this.startButton.disabled = true;
this.stopButton.disabled = false;
this.startListeners.forEach((callback) => { callback(this); });
});
this.stopButton = document.createElement('button');
this.stopButton.classList.add('timer__stop-button');
this.stopButton.textContent = 'Stop';
this.stopButton.disabled = true;
this.stopButton.addEventListener('click', () => {
this.startButton.disabled = false;
this.stopButton.disabled = true;
this.stopListeners.forEach((callback) => { callback(this); });
});
this.resetButton = document.createElement('button');
this.resetButton.textContent = 'Reset';
this.resetButton.classList.add('timer__reset-button');
this.resetButton.addEventListener('click', () => {
this.startButton.disabled = false;
this.stopButton.disabled = true;
this.resetListeners.forEach((callback) => { callback(this); });
});
this.elapsedTimeElement = document.createElement('p');
this.elapsedTimeElement.classList.add('timer__elapsed-time');
this.elapsedTimeElement.textContent = '0';
this.rootElement.append(this.startButton, this.stopButton, this.resetButton, this.elapsedTimeElement);
}
onStart(callback) {
this.startListeners.push(callback);
}
onStop(callback) {
this.stopListeners.push(callback);
}
onReset(callback) {
this.resetListeners.push(callback);
}
set elapsedTime(value) {
this.elapsedTimeElement.textContent = value;
}
get root() {
return this.rootElement;
}
}
let...