将有效负载添加到 vanilla JavaScript 事件

fir*_*dev 2 javascript jquery javascript-events

有没有办法像在 jQuery 中那样将有效负载添加到 vanilla JavaScript 事件?

// jQuery
$(document).trigger('event', payload);

// Vanilla JS
window.dispatchEvent(new Event('event', ???
Run Code Online (Sandbox Code Playgroud)

我想我必须使用我自己的某种事件总线?

gue*_*314 6

尝试利用CustomEvent,请参阅创建和触发事件

function eventHandler(e) {
  console.log("detail:", e.detail);
}

window.addEventListener("build", eventHandler);

window.dispatchEvent(new CustomEvent("build", {"detail": {"abc":123}}));
Run Code Online (Sandbox Code Playgroud)