Emit event in JS from a looped php

I have a loop of a livewire component in php:

    {{-- my livewire component --}}

Inside my Livewire component I have a function called “addComment”, this is also in the listeners.

From inside the loop I have JS function that has to fire “addComment” only for that component:

window.livewire.emit('addComment', e.currentTarget.value, postId);

But because the component is rendered 15 times (loop) and “addComment” is on listening 15 times. For many reason I have to fire the event from JS and not from php wire:click.

I thought “emitSelft” sounded delicious, but I tried doing this in JS:

window.livewire.emitSelf('addComment', e.currentTarget.value, postId);

But it says emitSelf does not exist :frowning:

I don’t think emitSelf exists on the javascript side and unfortunately, emitTo doesn’t scope by component Id but by component name so it would effectively function the same as emitting to all your components.

If you need to call addComment on initialization and you only want it to be scoped to that component, you might want to check out wire:init:

You can have your component call $emitSelf upon initialization or just call the addComment method directly.

Although, it does feel like there’d be a better way to accomplish what you need but there’s not enough code to determine that. Hopefully wire:init gets you where you want to go.

Dear shortbrownman, thanks a lot.
Unfortunately the action is not called on initialisation but later on the chain.

Ok, then I guess the only way is to:

  1. Assign a unique id to the component
<div id="reply_component_{{$this->post->id}}">...</div>
  1. Get that element from JS like:
let component = document.getElementById('reply_component_'+postID)
  1. Get the wire:id of it with
let lw_component = window.livewire.find(component.getAttribute('wire:id'));
  1. Fire:

So that it fires ONLY on that component.

You can simplify that to @this.call('addComment')

@this is a blade directive that will return window.livewire.find(unique-component-id).

Can I call that in the JS?

(php blade file)

//something in JS here

If it’s all within the component, you should be able to do that. I just tried it out and it works for me.