将有效负载添加到vanilla JavaScript Event

时间:2015-05-31 05:24:06

标签: javascript jquery javascript-events

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

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

// Vanilla JS
window.dispatchEvent(new Event('event', ???

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

1 个答案:

答案 0 :(得分:3)

尝试使用CustomEvent,请参阅Creating and triggering events



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

window.addEventListener("build", eventHandler);

window.dispatchEvent(new CustomEvent("build", {"detail": {"abc":123}}));