JavaScript event handling is the core of building dynamic interactive web applications. While basic event handling (e.g., addEventListener
) is simple, advanced patterns allow developers to optimize performance, handle complex user interactions, and write easy-to-maintain code.
This article explores advanced event handling patterns in JavaScript and provides practical examples to improve your event handling skills.
What is event delegation?
Event delegation refers to attaching a single event listener to a parent element to manage events for its child elements. This mode is particularly useful for elements that are dynamically added to the DOM after the page loads.
Example:
<code class="language-javascript">document.getElementById("parent").addEventListener("click", function(event) { if (event.target && event.target.matches(".child")) { console.log("点击了子元素:", event.target.textContent); } });</code>
Why use event delegation?
What are they?
Example:
Throttling
<code class="language-javascript">function throttle(func, limit) { let lastCall = 0; return function(...args) { const now = Date.now(); if (now - lastCall >= limit) { lastCall = now; func.apply(this, args); } }; } window.addEventListener( "resize", throttle(() => { console.log("窗口大小已调整!"); }, 200) );</code>
Anti-Shake
<code class="language-javascript">function debounce(func, delay) { let timer; return function(...args) { clearTimeout(timer); timer = setTimeout(() => func.apply(this, args), delay); }; } const searchInput = document.getElementById("search"); searchInput.addEventListener( "input", debounce(() => { console.log("输入事件触发!"); }, 300) );</code>
Why use them?
What are they?
Custom event emitters allow developers to create, dispatch and listen to their own events for increased modularity.
<code class="language-javascript">const eventEmitter = { events: {}, on(event, listener) { if (!this.events[event]) this.events[event] = []; this.events[event].push(listener); }, emit(event, data) { if (this.events[event]) { this.events[event].forEach((listener) => listener(data)); } }, }; eventEmitter.on("dataReceived", (data) => { console.log("收到数据:", data); }); eventEmitter.emit("dataReceived", { id: 1, message: "Hello!" });</code>
Why use them?
What is one-time event processing?
Sometimes you only need an event handler to execute once. Modern JavaScript provides an elegant way to handle this problem.
Example
<code class="language-javascript">const button = document.getElementById("myButton"); button.addEventListener( "click", () => { console.log("按钮被点击!"); }, { once: true } );</code>
Why use it?
What is event handler composition?
Event handler composition involves combining multiple handlers to handle events sequentially.
Example
<code class="language-javascript">function composeHandlers(...handlers) { return function(event) { handlers.forEach((handler) => handler(event)); }; } function logClick(event) { console.log("点击:", event.target); } function changeBackground(event) { event.target.style.backgroundColor = "yellow"; } document.getElementById("myElement").addEventListener( "click", composeHandlers(logClick, changeBackground) );</code>
Why use it?
What are they?
JavaScript event flow is divided into two stages:
Example
<code class="language-javascript">document.getElementById("parent").addEventListener("click", function(event) { if (event.target && event.target.matches(".child")) { console.log("点击了子元素:", event.target.textContent); } });</code>
Why use it?
What are they?
preventDefault()
Prevent default browser actions (e.g. form submission). stopPropagation()
Prevents events from propagating to other listeners. Example
<code class="language-javascript">function throttle(func, limit) { let lastCall = 0; return function(...args) { const now = Date.now(); if (now - lastCall >= limit) { lastCall = now; func.apply(this, args); } }; } window.addEventListener( "resize", throttle(() => { console.log("窗口大小已调整!"); }, 200) );</code>
Why use it?
Advanced event handling patterns are essential for building efficient, interactive, and easy-to-maintain JavaScript applications. By mastering techniques like event delegation, throttling, custom emitters, and propagation controls, you can tackle complex use cases with ease.
The above is the detailed content of Advanced Event Handling Patterns in JavaScript. For more information, please follow other related articles on the PHP Chinese website!