Creating maintainable JavaScript code is important if want to keep using the code.
In this article, we’ll look at the basics of creating maintainable JavaScript code by looking at separating app logic from event handling.
Also, we look at how to check for primitive values.
When we’re handling events, we should keep the event
object in the event handler only.
This will reduce coupling in our code.
So if we need to use something from the event
object, we keep them in the event handler.
For instance, we can write:
function onclick(event) {
const {
clientX,
clienty,
preventDefault,
stopPropagation
} = event;
preventDefault();
stopPropagation();
showPopup(clientX, clienty);
}
function showPopup(x, y) {
const popup = document.getElementById("popup");
popup.style.left = `${x}px`;
popup.style.top = `${y}px`;
popup.className = "popup";
}
const button = document.querySelector('button');
button.addEventListener('click', onClick);
We called the preventDefault
and stopPropagation
methods in from the event
object in the event handler.
This is much better than passing the event
object and call it in that function.
We don’t want our app logic code and event handling code to mix.
This way, we can change the app logic and event handling code independently.
And we can call the app logic code directly.
So we can write something like:
showPopup(10, 10);
It also makes testing a lot easier since we can call showPopup
directly to test it.
#technology #javascript #web-development #programming #software-development