2017-09-18 71 views
0

我試圖在使用turbolinks自定義錯誤處理方法後將turbolinks和trix一起工作,其中我使用從服務器發送的html替換文檔正文。使用Tubolinks重新初始化trix編輯器

// 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> 

有沒有辦法重新生成trix編輯器,還是我必須忘記在json中替換文檔的主體?

回答

0

這是我的解決辦法:

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) 
    } 
});