Key principles for effective and safe event management in JavaScript applications.
1// 1. Always check if the element exists
2const button = document.getElementById('my-button');
3if (button) {
4 button.addEventListener('click', handleClick);
5} else {
6 console.warn('Button with ID "my-button" was not found');
7}
8
9// 2. Use delegation for dynamic elements
10const parent = document.getElementById('dynamic-content');
11parent.addEventListener('click', (e) => {
12 if (e.target.matches('.dynamic-button')) {
13 handleDynamicButtonClick(e);
14 }
15});
16
17// 3. Remember to clean up event listeners
18class ParkComponent {
19 constructor(element) {
20 this.element = element;
21 this.handleClick = this.handleClick.bind(this);
22 this.init();
23 }
24
25 init() {
26 this.element.addEventListener('click', this.handleClick);
27 }
28
29 handleClick(e) {
30 console.log('Park component clicked');
31 }
32
33 destroy() {
34 this.element.removeEventListener('click', this.handleClick);
35 }
36}
37
38// 4. Use preventDefault() consciously
39const form = document.getElementById('contact-form');
40form.addEventListener('submit', (e) => {
41 e.preventDefault(); // Stops the default form submission
42
43 // Custom validation and submission logic
44 if (validateForm()) {
45 submitFormAjax();
46 }
47});