简体   繁体   English

如何取消侦听器中的自定义 javascript 事件?

[英]How to cancel a custom javascript event in a listener?

If a custom event created via CustomEvent is dispatched, what is the method to cancel it in listeners to prevent event's main purpose?如果调度了通过CustomEvent创建的自定义事件,在侦听器中取消它以防止事件的主要目的的方法是什么?

Eg An overlay is clicked by a user, then it emits an event, but it must be up to some code to decide if to hide the overlay or leave it untouched.例如,用户点击了一个覆盖层,然后它会发出一个事件,但必须由一些代码来决定是隐藏覆盖层还是保持不变。

UPDATE It's a share-knowledge question, I know the answer but try to impart it to the others.更新这是一个知识共享问题,我知道答案,但尝试将其传授给其他人。

We need to configure the event as cancellable我们需要将事件配置为cancellable

// create an event
let awesomeEvent = new CustomEvent('some_awesome_event', {
    cancelable: true
})
// emit
let isAllowed = window.dispatchEvent(awesomeEvent)

Call preventDefault inside any event listener to cancel it.在任何事件侦听器中调用preventDefault以取消它。

window.addEventListener('some_awesome_event', event => {
    event.preventDefault()
})

Then it is possible to check whether the event was cancelled with the result returned from dispatchEvent然后就可以用dispatchEvent返回的结果来检查事件是否被取消了

let isAllowed = window.dispatchEvent(awesomeEvent)
if(isAllowed){
    // do some default things
}
else {
    // just an example
    console.log('Oops! The event was cancelled, nothing to do...')
}

MDN guide for events creation and triggering事件创建和触发的MDN 指南

preventDefault documentation 防止默认文档

cancellable interface docs 可取消的接口文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM