如何解雇自定义可取消事件

时间:2017-03-11 06:46:33

标签: javascript events

我知道如何在JavaScript中触发事件,但我不知道如何使其可取消。在事件处理程序中通过event.preventDefault()

document.dispatchEvent(new CustomEvent("name-of-event", {}));

我已经编写了以下代码,但是如何通过event.preventDefault()以原生方式实现?

document.dispatchEvent(new CustomEvent("my-event",function keepGoing(result){
  if(result){
      // continue ...
  }
}));

// And then in event listener:
document.addEventListener('my-event',function(event,keepGoing){
keepGoing(true);
// Or keepGoing(false);
});

2 个答案:

答案 0 :(得分:6)

CustomEvent构造函数采用第二个选项参数,您可以使用该参数创建事件cancelable。请参阅MDN上的文章Creating and triggering events



var event = new CustomEvent("my-event", {
  cancelable: true
})

document.addEventListener('my-event', function (event) {
   event.preventDefault()
})

console.log(
  document.dispatchEvent(event) ? 'Event was not cancelled' : 'Event was cancelled'
)




答案 1 :(得分:3)

CustomEvent构造函数接受CustomEventInit作为第二个参数。 CustomEventInit是此处描述的EventInit的扩展https://developer.mozilla.org/en-US/docs/Web/API/Event/Event

最后。

document.dispatchEvent(new CustomEvent('my-event', {cancelable: true}));