Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In vue, how do I check if any parent component has subscribed for an event which child is emitting?

I have a component which is sometimes being used as a child of a parent and sometimes it does not have any parent.

This component emits a particular event which either being caught by the parent ( if subscribed) or I would like to handle it by this component itself.

So at run time, How do I programmatically check

if (someone is listening to the event){
    let them catch and handle it
}else {
    let's handle it by our own
}
like image 524
Amit Gore Avatar asked Sep 15 '25 10:09

Amit Gore


1 Answers

This allows you to check listeners passed to a component:

this.$listeners;

It returns the parent scope event listeners. See the doc here.

In particular for your use-case:

// To check whether the "myEvent" event is listened to
if (this.$listeners.myEvent){
  // let them catch and handle it
} else {
  // let's handle it by our own
}
like image 126
bernie Avatar answered Sep 17 '25 22:09

bernie