How to prevent events from triggering in parent components?

I have a set of nested components of the same type. When an event is fired in a child component, it is also caught in all parent components all the way up the chain. Is there a way to prevent events from bubbling up?

Did you try to scoping the events to itself?
You can find the explanation in the documentation under scope events to self.

Thanks @leMaur, unfortunately that doesn’t seem to actually exist:

TypeError: window.livewire.emitSelf is not a function.

This has also been reported in GitHub to not be working: https://github.com/livewire/livewire/issues/833

I have eliminated the javascript events from triggering on both components, by passing and checking the component id. Instead, I believe this has to do with changes to the internal state of the child component also being applied to the parent component (as they are the same component with nested instances).

Have you tried emit tô a.specific component?

That won’t help, because both the parent and the child components are of the same type. So in going with the example, the parent and child are both counter components. Additionally, I don’t think it’s a javascript event issue, but rather an PHP component instance issue.

I’m also getting the following error now when triggering an event from the child-component:

Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'store.findComponent(payload.id).receiveMessage')

code:

                axios
                    .post(this.action, formData)
                    .then(function (response) {
                        console.log("test1");
                        window.livewire.emit('updateSelectedItem', response.data);
                        console.log("test2");
                    })
                    .catch(function (error) {
                        if ((((error || {}).response || {}).status || 200) === 422) {
                            window.livewire.emit('setErrors', error.response.data, id);
                        } else {
                            console.error(error);
                        }
                    });

Has anyone encountered this before?

You could probably leverage dynamic listeners to name them to the component.

protected function getListeners()
{
    return ['postAdded' . $someName => 'showPostAddedMessage'];
}

It might also be possible to leave the $listeners empty and add one as needed, but I’ve never tried and I don’t know if they have to exist on the initial load to work or not.

2 Likes

Wow … I had done that in the past in testing, and it didn’t help. In combination with some of the other changes I have made since then, it seems to work marvelously!!! Thanks so much!