Is there any way of passing additional data via custom events?
Solution 1:
Yes, you can use a MessageEvent
or a CustomEvent
.
Example usage:
//Listen for the event
window.addEventListener("MyEventType", function(evt) {
alert(evt.detail);
}, false);
//Dispatch an event
var evt = new CustomEvent("MyEventType", {detail: "Any Object Here"});
window.dispatchEvent(evt);
Solution 2:
pass object with more details as attributes:
var event = new CustomEvent('build', { detail: { 'detail1': "something", detail2: "something else" }});
function eventHandler(e) {
log('detail1: ' + e.detail.detail1);
log('detail2: ' + e.detail.detail2);
}
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
Solution 3:
new CustomEvent
is not supported in IE https://caniuse.com/#search=CustomEvent
Here is a version which also works on IE9+:
//Listen for the event
window.addEventListener("MyEventType", function(evt) {
alert(evt.detail.test); //alerts "Any Object Here"
}, false);
//Dispatch an event
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent('MyEventType', false, false, { test: "Any Object Here" });
window.dispatchEvent(evt);