reinitialize trix editor with Tubolinks

658 views Asked by At

I am trying to get turbolinks and trix to work together after using a custom error handling method with turbolinks where I replace the body of the document with html sent from the server.

// administration.js

import Rails from 'rails-ujs'
import Turbolinks from 'turbolinks'
import Trix from 'trix'
Rails.start();
Turbolinks.start();

// TURBOLINKS - ERROR HANDLING
document.addEventListener("ajax:error", (e) => {
  if (e.detail[2].status !== 422) { return }
  document.body = e.detail[0].body
  Turbolinks.dispatch("turbolinks:load")
  scrollTo(0, 0)
})

<!-- form.html -->
<div class="small-10 columns">
  <input type="hidden" id= "body" %>
  <trix-editor input="body"></trix-editor>
</div>

Is there a way to reinitalize the trix editor or do I have to forget replacing the body of the document in json ?

1

There are 1 answers

0
Snake On

This is my fix :

html : 
<%= f.hidden_field :body, id: "body", data: { behavior: "trix-editor" } %>

js :
document.addEventListener("turbolinks:load", () => {
  const trixField = document.body.querySelector("[data-behavior='trix-
  editor']")
  if (document.body.contains(trixField)) {
    const fieldId = trixField.attributes["id"].value
    const trixEditor = document.createElement("trix-editor")
    trixEditor.setAttribute("input", fieldId)
    const parentDiv = trixField.parentNode
    parentDiv.insertBefore(trixEditor, trixField)
   }
});