Handle afterDomUpdate for component

Hi.

I have a component with a script portion (pushed to scripts stack) in which I want to do something after the DOM is updated. I have something like this:

document.addEventListener("livewire:load", function(event) {
    window.livewire.afterDomUpdate(() => {
        doSomething();
        doEvenMoreStuff();
    });
});

The problem is this event is getting caught by other Livewire components in the page and I want to apply it only for the one in which it is defined.

Is there a way to compare something in the event parameter with @this in order to find out if it is the right component?

I would set that up as a “global” listener. As in put it where it gets compiled into your app.js. Then fire a doSomething event there, and listen for it in your component to trigger the doSomething() method in your component.

Wouldn’t that also be picked up by other components as well? That’s my problem.

Nope. Let’s say you have 2 components. Component1 has doSomething() and Component2 has doSomethingElse().

window.livewire.emit('fireDoSomething') in your javascript, and put a listener in Component1 protected $listeners = ['fireDoSomething' => 'doSomething'];

Component1 will trigger the doSomething() method, and Component2 wont do anything because nothing is telling it to doSomethingElse()

Maybe I didn’t express myself correctly.

What I want is to do something on client side, after the DOM is updated (after the Livewire component renders). doSomething has nothing to do with Livewire, it’s vanilla JS (or some other client side library call). I just want to bind it to Livewire component update.

I’m not horribly great with javascript, so there’s probably a better way, but I think this will work:

document.addEventListener("livewire:load", function(event) {
    window.livewire.afterDomUpdate(() => {
        search = Object.values(livewire.components.componentsById).find((component) => component.name == "yourComponentName")
        if (typeof search !== "undefined") {
            doSomething();
            doEvenMoreStuff();
        }
    });
});

There’s been a Livewire update that solves your issue, I think.

Yes, ignore my comment, your specific issue has been addressed in 0.7.1.

Using 0.7.1 I can run my code after DOM is updated. I’m doing something like:

window.livewire.hook('afterDomUpdate', (component) => {
    if (component.id == @this.id) {
        doSomething();
        doEventMoreStuff();
    }
});

This works fine but I feel I should be able to add the hook to the component that declares it. Maybe something like:

window.livewire.hook('afterCurrentComponentDomUpdate', (component) => {
    ...
});

And Livewire would translate it to something that would tap the afterDomUpdate hook only for the current component.