Encapsulation of html and javascript

I have a Livewire component that contains some javascript & html code that I now realise will appear multiple times on a page.
I don’t suppose there is an easy way of encapsulating everything so that they do not conflict with eachother (?)

Hi,

I’m not sure how you’re set up but you could look at stacks, https://laravel.com/docs/8.x/blade#stacks and then instead of adding the scripts to the child component you can push the scripts to the stack from the parent component.

<div>

    <livewire:child-component></livewire:child-component>

    <livewire:child-component></livewire:child-component>

    <livewire:child-component></livewire:child-component>

</div>

@push('scripts')

    <!-- Scripts Here -->

@endpush

This way you’re including the scripts only once and not for each component.

Hope this helps.

1 Like

Thanks, I’ll check that out. I suspect that won’t help me though because I have lots of IDs in the HTML UI (e.g. container boxes) and they’re going to need unique IDs. That might be good for the JS though if I can figure out how to make that generic.

No problem. I think it will just depend on how you’re developing your project I suppose, but doing it this way will still allow you to target the IDs. As for making things generic in Javascript you could use classes and loop through the node list instead?

1 Like