Event listener not working in laavel 7

Even listener not working on laravel 7.

This was places in my view that has a corresponding component
<button wire:click="$emit('postAdded','78')">Click</button>

Then this in script tag

<script>
  window.livewire.on('postAdded', postId => {
      alert('A post was added with the id of: ' + postId);
  })
</script>

But refuse to work

2 Likes

Are you showing any errors in your console?

Yes, Just noticed the error now in my console:
Uncaught TypeError: Cannot read property ‘on’ of undefined

from: image

I dont know why the error is showing pleases help

It’s telling you that javascript doesn’t have a livewire object. It sounds like you are missing the @livewireScripts (and possibly the @livewireStyles) https://laravel-livewire.com/docs/quickstart/

It’s possible that you set them up in blade somewhere, but the current page you are on isn’t using that portion of blade.

I fixed it i put the livewirescript before the javascript tag that fixed it

@livewireScripts

<script>

  window.livewire.on('postAdded', postId => {

      alert('A post was added with the id of: ' + postId);

  })

</script>