Javascript 简明教程

JavaScript - Custom Events

Custom Events

JavaScript 中的自定义事件定义和处理应用程序中的自定义交互或信号。它们建立了各种代码部分之间的通信机制:一部分可以通知其他部分特定事件或更改;因此增强了程序的功能。

The custom events in JavaScript define and handle custom interactions or signals within an application. They establish a communication mechanism between various sections of your code: one part can notify others about specific occurrences or changes; thus enhancing the functionality of your program.

通常,用户将自定义事件与 Event 和 CustomEvent 接口结合使用。以下是其功能的详细细分:

Typically, users utilize custom events in conjunction with the Event and CustomEvent interfaces. The following provides a detailed breakdown of their functionality:

Concept

Description

Custom Event

The CustomEvent constructor in JavaScript facilitates communication between various parts of an application by defining a user-specific event. Such custom events manifest as instances of this constructor.

CustomEvent Constructor

The built-in JavaScript constructor creates custom events, utilizing two parameters: the event type, a string, and a discretionary configuration object; for instance, an optional detail property can be used to provide supplementary data.

dispatchEvent Method

A method available on DOM elements that dispatches a custom event. It triggers the execution of all listeners for that event type on the specified element.

addEventListener Method

A method available on DOM elements to attach an event listener function to an event type. The listener function is executed when the specified event is dispatched on the element.

Event Types

Strings that identify the type of event. Custom events can have any user-defined string as their type.

Event Handling

Listening for and responding to events is an active process. It primarily involves the creation of listeners for specific event types in custom contexts, and subsequently defining precise actions that will occur when these events take place.

Pub/Sub Pattern

In this design pattern, system components communicate with each other indirectly and without direct references. By utilizing custom events, one can implement a publish/subscribe pattern that enables various application sections to subscribe to specific events and react accordingly.

detail Property

An optional property in the configuration object when creating a custom event. It allows you to pass additional data (as an object) along with the event.

Example: Basic Custom Event

在此示例中,我们启动名为“myCustomEvent”的自定义事件并渲染一个关联按钮。利用addEventListener方法,我们跟踪此按钮触发的事件。单击该按钮时,我们的操作将分发自定义事件;随后弹出消息“触发自定义事件!”

In this example, we initiate a custom event named 'myCustomEvent' and render an associated button. Using the addEventListener method, we track events triggered by this button. Upon clicking the button, our action dispatches the custom event; subsequently alerting a message "Custom event triggered!"

<!DOCTYPE html>
<html>
<body>
<button id="triggerBtn">Trigger Event</button>
	<script>
		// Creates the new custom event.
		const customEvent = new Event('myCustomEvent');
		// Adds an event listener to the button.
		document.getElementById('triggerBtn').addEventListener('click',
		function() {
			// Dispatches custom event on button click.
			document.dispatchEvent(customEvent);
		});
		// Add listener for the custom event.
		document.addEventListener('myCustomEvent', function() {
			alert('Custom event triggered!');
		});
	</script>
</body>
</html>

Example: Custom Event with Data

在本示例中,我们将使用CustomEvent,它作为接口并且扩展了主要的事件。在此我们将演示detail属性,它可让我们设置附加数据。自定义事件名称为“myCustomEventWithData”,它还将包含关联消息。单击按钮时将会分发此自定义事件。如果单击此按钮,则此事件将被触发并在屏幕上弹出设置的消息。

In this example we will make use of the CustomEvent which is an interface and extends the primary Event. The detail property will be demonstrated here which allows us to set additional data. The custom event name will be 'myCustomEventWithData' and it will have a message associated to it. This custom event will be getting dispatched upon the click of a button. When this button is clicked, this event will be triggered and the message set will be alerted on screen.

<!DOCTYPE html>
<html>
<body>
	<button id="triggerBtn">Trigger Custom Event</button>
	<script>
		const eventData = { message: 'Hello from custom event!' };
		const customEvent = new CustomEvent('myCustomEventWithData',
		{ detail: eventData });
		document.getElementById('triggerBtn').addEventListener('click',
		function() {
			document.dispatchEvent(customEvent);
		});
		document.addEventListener('myCustomEventWithData',
		function(event) {
			alert('Custom event triggered with data: ' + event.detail.message);
		});
	</script>
</body>
</html>

Example: Condition-based Event Dispatching

此示例阐明了一个场景:事件分发严格依赖于变量(v),其中基于条件。它强调您应用程序对自定义事件的动态使用,取决于特定条件。本例的情况涉及根据v值分派“ TutorialEvent”或“ TutorialEvent2”;相应地,事件侦听器将根据此选择作出反应。

This example illuminates a scenario: event dispatching critically hinges on a variable (v), being conditionally based. It underscores your application’s dynamic use of custom events, dependent upon specific conditions. The case at hand involves the dispatching either 'TutorialEvent' or 'TutorialEvent2' determined by the value of v; correspondingly, an event listener reacts accordingly to this choice.

<!DOCTYPE html>
<html>
<body>
	<script>
		var v='tutorialspoint';
		const event = new Event("TutorialEvent");
		const event2 = new Event("TutorialEvent2");

		document.addEventListener('TutorialEvent', ()=>{
			alert("Welcome to Tutorialspoint Event")
		});
		document.addEventListener('TutorialEvent2', ()=>{
			alert("Welcome to Event 2")
		});

		if(v == 'tutorialspoint'){
			document.dispatchEvent(event);
		}
		else{
			document.dispatchEvent(event2);
		}
	</script>
</body>
</html>

总结创建自定义事件的步骤,我们首先创建事件或自定义事件,使用addEventListener(最好使用此方法)添加侦听器,然后我们使用dispatchEvent 方法触发或分发事件。

To summarize the steps for creating custom events, we first create an event or Custom event, add the listener using the addEventListener (preferably) and then we trigger or dispatch the event using the. dispatchEvent method.