Javascript Events and Decoupling

事件是JavaScript开发中的关键工具,它们实现了发布-订阅模式,有助于解耦DOM和JavaScript程序。通过监听DOM节点上的事件,可以实现多个独立脚本对同一事件的响应。自定义事件进一步增强了这种能力,允许开发者创建自定义事件并在DOM中传播,以此来传递信息并保持代码的清洁和模块化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

How using native and custom events in your programs helps to simplify and modularize.

Alex Zito-Wolf

Alex Zito-Wolf

May 2·2 min read

Events are one of the single most important tools in your development toolkit as a JS developer. Whenever you want to have your script react to any user interaction on the page — a scroll, a mouse click, a tap on the back button, etc., you will generally write an ‘event listener’ into your script. In vanilla JS, that will be something like:

document.addEventListener(‘mousedown’, () => {    alert('you just clicked something');})

In the above code snippet, you are adding an event listener on the highest level node in the DOM tree: the document node. All of the elements in the DOM are descendants of this node. If you don’t know too much about the concept of nodes, I recommend this introductory article from MDN.

Decoupling with Events

Events are fantastic because they implement a pub-sub software pattern. Pub sub stands for publish subscribe’, and it is one of the tried and true methods of decoupling two software systems from on another.

In the case of Javascript Events, the two systems that are being decoupled are the DOM and the Javascript program that you have written as the developer.

As long as your script has access to the browsers DOM methods (which is always) you will be able to add a listener to any of the nodes in the DOM and watch that event. ALL of your scripts will have the same experience. When the scroll even fires in the browser, events from many disparate scripts can fire off. This is really valuable because the event itself is completely separate from the listener methods that might be reacting to it.

Custom Events

Javascript also allows you to create custom events, that bubble up in the same way and provide the same great advantages of decoupling the event from the listeners.

You create a custom event like this:

const event = new CustomEvent('dropdownSelect');

You then need to dispatch the event which will set the event bubbling up in the DOM:

dispatchEvent(event);

You will then be able to listen to the event anywhere in the DOM:

document.addEventListener('dropDownSelect', () => {     // this is where you can react to that event
    reactToTheDropdownChangeEvent();});

I find myself using custom events for all sorts of things, dropdown events, clicks that trigger modal openings, and global events like language changes.

You’ll of course want to send information along with the event. That can be handled like so:

const event = new CustomEvent('componentClickable', { detail: Date.now() });

This will then allow you to access the additional data in the event listener:

function eventHandler(e) {
  console.log('The component took ${e.detail} seconds to load');
}

By hooking into this DOM API, you will be able to reduce dependencies between your scripts and more fully modularize your scripts. Instead of having a function inside of your language toggle that has 15 callback registered to it, you can create a single event called “languageToggle” that has 15 different listeners, across 15 different scripts. This helps to keep code clean and modular.

Happy coding,

~ Alex Zito-Wolf

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值