4

Component Billy can dispatch an event:

this.dispatchEvent(new CustomEvent('stuffHappened'));

Can Billy know if its parent provided a handler for that event?

Can it know if it was called like this:

<c-billy onstuffhappened={handler}></c-billy>

as opposed to simply like this:

<c-billy></c-billy>

Is there a way to see all the HTML attributes on <c-billy>?

2
  • You'd want to create a "promise" that returns "true" or "false" in a handler method.
    – crmprogdev
    Aug 3, 2021 at 12:11
  • 2
    @crmprogdev how would this solve the question?
    – Damecek
    Aug 3, 2021 at 12:13

1 Answer 1

5

No. Strictly speaking, unless you come up with some arrangement with the parent, you cannot tell if an event was actually handled. What would that look like?

@api eventHandled() {
  if(this.eventFired) {
    console.log('someone got my message!');
  }
  this.eventFired = false;
}
someHandler() {
  this.dispatchEvent(new CustomEvent('stuffhappened'));
}

...

stuffHappenedHandler(evernt) {
  event.target.eventHandled();
}

Obviously, this requires that the parent honor billy's interface and informs them of an event handled.

I wrote up a demo for you.

Note that this covers only the situation where the parent decides to respond. If the parent chooses not to tell, then billy will never be notified, though it can tell that the parent never responded in a later function call (in the demo, we set a flag to remember if we fired a message).

There is a way to reflect attributes, but this only works for standard DOM properties, like title or tabindex. You can't use it to detect event handlers, as far as I can tell (also in the demo).

1
  • Hey @sfdcfox (of course it's you), great answer, thank you. My main question was if I can see in advance if a handler has been provided at all, but this answers even more actually. I didn't know about reflecting with .getAttribute() method, that would have been perfect, too bad it doesn't work here.
    – Bloke
    Aug 8, 2021 at 13:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .