自定义事件
JavaScript 中的自定义事件定义和处理应用程序中的自定义交互或信号。它们在代码的各个部分之间建立了通信机制:一个部分可以通知其他部分特定事件或更改;从而增强程序的功能。
通常,用户将自定义事件与 Event 和 CustomEvent 接口结合使用。下面提供了其功能的详细分类:
示例:基本自定义事件
在此示例中,我们启动一个名为 'myCustomEvent' 的自定义事件并呈现一个关联的按钮。使用 addEventListener 方法,我们跟踪此按钮触发的事件。单击该按钮后,我们的 action 会 dispatch 自定义事件;随后提醒一条消息“Custom event triggered!”
<!DOCTYPE html>
<html>
<body>
<button id="triggerBtn">Trigger Event</button>
<script>
// 创建新的自定义事件。
const customEvent = new Event('myCustomEvent');
// Adds an event listener to the button.
document.getElementById('triggerBtn').addEventListener('click',
function() {
// 单击按钮时发送自定义事件。
document.dispatchEvent(customEvent);
});
// 为自定义事件添加侦听器。
document.addEventListener('myCustomEvent', function() {
alert('Custom event triggered!');
});
</script>
</body>
</html>
示例:包含数据的自定义事件
在此示例中,我们将使用 CustomEvent,它是一个接口并扩展主事件。这里将演示 detail 属性,它允许我们设置额外的数据。自定义事件名称将为 'myCustomEventWithData',并且将有一条与之关联的消息。此自定义事件将在单击按钮时被调度。单击此按钮时,将触发此事件,并在屏幕上提醒消息集。
<!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>
示例:基于条件的事件调度
这个例子说明了一个场景:事件调度关键地取决于一个变量 (v),它是基于条件的。它强调应用程序根据特定条件动态使用自定义事件。手头的情况涉及由 v 的值确定的 'TutorialEvent' 或 'TutorialEvent2' 的分派;相应地,事件侦听器会相应地响应此选择。
<!DOCTYPE html>
<html>
<body>
<script>
var v='qikepu';
const event = new Event("TutorialEvent");
const event2 = new Event("TutorialEvent2");
document.addEventListener('TutorialEvent', ()=>{
alert("Welcome to qikepu Event")
});
document.addEventListener('TutorialEvent2', ()=>{
alert("Welcome to Event 2")
});
if(v == 'qikepu'){
document.dispatchEvent(event);
}
else{
document.dispatchEvent(event2);
}
</script>
</body>
</html>
为了总结创建自定义事件的步骤,我们首先创建一个事件或自定义事件,使用 addEventListener(最好)添加侦听器,然后使用 触发或分派事件。dispatchEvent 方法。