Re-initialising js plugin after livewire render

Viewed 370

How do I initialise a plugin on a component after validation fails?

I have a textarea that line numbers gets added to via JS.

On submit, the textarea is then validated. If validation fails, it renders a normal textarea. I used the element.initialized hook and it worked, but only once - so basically: form is loaded and textarea initialised. It fails validation, and textarea is initialised again. Then it fails validation again, and textarea is the plain, vanilla textarea.

This is the text area:

<textarea class="border-gray-300 block w-full focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 shadow-sm rounded-none rounded-md" name="results" rows="10" wire:model.defer="unprocessedResults" id="results-textarea"></textarea>

This is my js:

document.addEventListener('livewire:load', function() {
    TLN.append_line_numbers('results-textarea');
    Livewire.hook('element.initialized', function(el, component) {
        TLN.append_line_numbers('results-textarea');
    })
});

How do I solve this?

1 Answers

The best option here would be to use wire:ignore or wire:ignore.self on that element. That would mean that Livewire will not touch that element when it does its DOM-diffing. This means, that other JavaScript libraries will remain in their state, if they are manipulating the DOM themselves.

<textarea
    class="border-gray-300 block w-full focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 shadow-sm rounded-none rounded-md"
    name="results"
    rows="10"
    wire:ignore
    wire:model="unprocessedResults"
    id="results-textarea"></textarea>
Related