javascriptevent-handlingpolymerdom-eventspolymer-2.x

Return data to component that dispatches event


I have a deeply nested web component that dispatches an event with data:

this.dispatchEvent(new CustomEvent('do-something', {
  bubbles: true,
  composed: true,
  detail: {
    itemId: itemId
  }
}));

I would like to conditionally handle the event.detail in a parent element and then return data back to the component that dispatched the event.

Currently I am selecting child nodes from parent nodes declaratively by id and passing the data back down through several functions.

passDataToFirstChild() {
  this.$.firstChildNode.property = this.dataComputedByParent.
}

...

passDataToSecondChild() {
  this.$.secondChildNode.property = this.dataPassedFromFirstChild.
}

Is there a way to shortcut this process?

I see that the event object has a path property, but I am not seeing an obvious way to integrate that array into a solution that would hook the child and parent node together.

So, is there a way to directly connect a deeply nested child node with a parent node to pass data back and forth via events?


Solution

  • In the event detail you can send the reference of the node that dispatched the event.

    this.dispatchEvent(new CustomEvent('do-something', {
      bubbles: true,
      composed: true,
      detail: {
        itemId: 'item id', 
        dispatcher: this
      }
    }));
    

    Listener in some parent

    this.addEventListener('do-something', (e) => {
        e.detail.dispatcher.property = this.dataComputedByParent;
    })