Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispatch event with data

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" }) 
like image 775
nicholaswmin Avatar asked May 18 '14 19:05

nicholaswmin


People also ask

What is a dispatch event?

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.

How do I use dispatch event?

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.

What is dispatch event in Salesforce?

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.

Is dispatchEvent synchronous?

It's guaranteed to be synchronous because: The return value of dispatchEvent indicates whether any of the listeners which handled the event called preventDefault.


1 Answers

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); }); 
like image 157
adnan kamili Avatar answered Sep 22 '22 01:09

adnan kamili