I'd like to dispatch an event that will pass some data to any event listeners that listen on that event.
Considering a function that fires an event:
function click() { const x = 'foo' document.dispatchEvent(new CustomEvent('clicked')) } click()
How can I pass custom data to the event listener?
document.addEventListener('clicked', function(e) { console.log(x) // logs "foo" })
dispatchEvent is what you call if you want to send or trigger an event. Internally, the browser is doing this whenever the user rotates their device, which triggers orientationchange . In this specific example, you don't need to trigger this manually unless you need to do so for testing.
Use the specific event constructor such as MouseEvent and call dispatchEvent() method on an element to generate an event from code. Use event. isTrusted to examine whether the event is generated from code or user actions.
When a user clicks to select a contact, the component creates and dispatches a CustomEvent called selected . The event includes the data detail: this.contact.Id , which is the ID of the selected contact. The parent, c-event-custom , uses the contact reference to display more information about the contact.
It's guaranteed to be synchronous because: The return value of dispatchEvent indicates whether any of the listeners which handled the event called preventDefault.
Perhaps you are looking for event.detail
new CustomEvent('eventName', {'detail': data})
Instead of data use x and in event listener you can access x using event.detail
function getSelectionBounds() { var x = (bounds["x"].toFixed(2)); var y = "xyz"; var selectionFired = new CustomEvent("selectionFired", { "detail": {"x":x,"y":y } }); document.dispatchEvent(selectionFired); }; document.addEventListener("selectionFired", function (e) { alert(e.detail.x+" "+e.detail.y); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With