Reader small image

You're reading from  JavaScript Design Patterns

Product typeBook
Published inMar 2024
Reading LevelIntermediate
PublisherPackt
ISBN-139781804612279
Edition1st Edition
Languages
Right arrow
Author (1)
Hugo Di Francesco
Hugo Di Francesco
author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco

Right arrow

Event-Driven Programming Patterns

Event-driven programming in JavaScript is very widespread and is the only way to handle certain scenarios. Maintaining performance and security around event listeners is of paramount importance. Mismanaged event listeners have been a historical source of bugs and critical performance issues; we’ll address this via the event delegation pattern. Secure messaging between frames and contexts has always been crucial in the context of payments. More recently, new primitives are being added to the web platform and JavaScript that exposes an event/messaging interface for maintaining isolation between contexts.

In this chapter, we’ll cover the following topics:

  • Implementing event delegation
  • Using the postMessage interface to communicate across contexts with an example of a payment iframe
  • Common event listener antipatterns and how to remediate them

At the end of this chapter, you’ll have learned how to use advanced...

Technical requirements

You can find the code files for this chapter on GitHub at https://github.com/PacktPublishing/Javascript-Design-Patterns

Optimizing event listeners through event delegation

Event delegation is a common event listener pattern used to go from “many elements, many event listeners” to a “many elements, single event listener.” At its core, event delegation attaches one event listener to the page’s Document, and inside that listener, it checks what the target of the event is in order to figure out how the event should be handled.

Event delegation means fewer listeners are attached. There’s only one per root node; if we’re doing event delegation at the document level, that means one listener. Another benefit is that DOM nodes can be attached and removed without worrying about adding or removing the relevant event listeners.

The following sequence diagram details an implementation of listening to clicks on two buttons.

Figure 8.1: Event handling without event delegation

Figure 8.1: Event handling without event delegation

Event handling without event delegation can be contrasted...

Patterns for secure frame/native WebView bridge messaging

Gaining a deep understanding of messaging patterns with postMessage in JavaScript is crucial for working in a variety of contexts. postMessage is defined on the following Web API objects: Window, MessagePort, Worker, Client, ServiceWorker, and BroadcastChannel.

In other words, postMessage-based messaging is useful for document-to-iframe, iframe-to-iframe, document-to-worker, and service worker-to-document communication and that’s only the Web APIs. Due to how widespread the postMessage API is, it’s also adopted in non-standard APIs for handling multiple JavaScript contexts. For example, web extensions for Chrome and Firefox contain multiple JavaScript contexts: the devtools panel, proxy, backend, and background script. The postMessage API is also used for Android and iOS communication between the native code and WebViews.

The scenario that we’ll go through is about iframes and how they communicate...

Event listener performance antipatterns

Event listener performance antipatterns change over time. For example, when Internet Explorer support was broadly required due to its market share, adding event listeners to DOM nodes and subsequently deleting the nodes would not clean up the event listeners, causing memory leaks. This doesn’t occur anymore in modern browsers.

An event listener antipattern that is often caught by the Lighthouse page performance auditing tool is scroll event listeners that aren’t set to be passive. Passive event listeners are more performant because event.preventDefault() doesn’t intercept and stop the event’s default behavior. This allows browsers to set the event listener to be non-blocking since the listener can’t act on the event.

Making an event listener passive simply involves passing { passive: true } as the third parameter to addEventListener():

document.addEventListener(
  'scroll',
 ...

Summary

In this chapter, we’ve covered advanced event-driven programming patterns to keep a JavaScript code base performant and secure when handling large numbers of events and event listeners.

Event delegation is useful to ensure that the number of event listeners doesn’t grow with the number of DOM nodes in a client-side application where elements are inserted and removed dynamically.

Patterns for secure frame messaging mean we’re able to orchestrate iframe initialization and bidirectional communication between an iframe and its parent document.

Finally, we covered common event listener performance antipatterns to avoid the common pitfalls of event listener-heavy code bases.

Now that we’re familiar with advanced event-driven programming patterns in JavaScript, in the next chapter, we’ll cover lazy-loading and code-splitting to maximize the performance of JavaScript applications.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
JavaScript Design Patterns
Published in: Mar 2024Publisher: PacktISBN-13: 9781804612279
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco