JavaScript reactivity with custom events
Without design patterns we can add native reactivity with custom events
In this short example I show how from a custom event we can inadvertently send messages to the browser from the same application. I use the object paradigm in JavaScript here. Simple and efficient.
JavaScript Object sample,
/*
CUSTOM EVENTS
File: drunk_events.js
*/
var eventArgs = {
message: ''
};
const drunkMessagesEvent = new CustomEvent("drunkMessages", {
detail: eventArgs
});
// CLASS
class Drunk extends Event {
constructor(name, limit) {
super('drunkMessages');
this.name = name;
this.limit = limit;
}
Drink() {
const name = this.name;
const limit = this.limit;
const task = setInterval(timingTask, 1000);
var count = 0;
function timingTask() {
count++;
if (count > limit) {
eventArgs.message = name + ' go to sleep';
// stop timing task
clearInterval(task);
} else {
eventArgs.message = 'Drinking ' + count + ' of ' + limit;
}
document.dispatchEvent(drunkMessagesEvent);
}
}
}
UI sample, index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Drunk</h1>
<div id="prompt"></div>
</body>
<script src="drunk_events.js"></script>
<script>
// testing
prompt = document.getElementById('prompt');
const drunk = new Drunk('Alice Cooper', 12);
drunk.Drink();
document.addEventListener("drunkMessages", e => {
prompt.textContent = e.detail.message;
});
</script>
</html>