I have a ponent which is sometimes being used as a child of a parent and sometimes it does not have any parent.
This ponent emits a particular event which either being caught by the parent ( if subscribed) or I would like to handle it by this ponent 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
}
I have a ponent which is sometimes being used as a child of a parent and sometimes it does not have any parent.
This ponent emits a particular event which either being caught by the parent ( if subscribed) or I would like to handle it by this ponent 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
}
Share
Improve this question
asked May 27, 2019 at 12:06
Amit GoreAmit Gore
4514 silver badges13 bronze badges
2 Answers
Reset to default 7This allows you to check listeners passed to a ponent:
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
}
You can pass a boolean prop from your parent.
In Parent Component :
<Child :isParent='true'></Child>
In Child Component :
props : {
isParent : Boolean
},
methods : {
actionEvent : function(){
if(this.isParent){
// Emit event
}
else{
// Take care over here.
}
}
}