有没有办法像在jQuery中一样将有效负载添加到vanilla JavaScript事件中?
// jQuery
$(document).trigger('event', payload);
// Vanilla JS
window.dispatchEvent(new Event('event', ???
我想我必须使用自己的某种事件总线?
答案 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}}));