使用 ActionText 时,
f.rich_text_area
呈现 Trix 编辑器。当我向编辑器添加附件时,它会自动开始直接上传。如果我在上传完成之前提交表单,显然文本中的附件将会丢失。我知道在上传开始之前,当附件“刚刚添加”时,会触发事件“trix-attachment-add
”。 我可以添加什么事件侦听器才能知道上传何时完成?
控制器:
// form-with-trix-controller.js
export default class extends Controller {
static targets = ['submit']
disableSubmitIfTrixAttachmentsUploading(/*event*/) {
const { hasTrixAttachmentsUploading } = this
this.submitTargets.forEach(submitTarget => submitTarget.disabled = hasTrixAttachmentsUploading)
}
get hasTrixAttachmentsUploading() {
return this.trixAttachments.some(attachment => attachment.isPending())
}
get trixAttachments() {
return this.trixElements.flatMap(trix => trix.editor.getDocument().getAttachments())
}
get trixElements() {
return Array.from(this.element.querySelectorAll("trix-editor"))
}
}
在包装 Trix 控制器的表单中:
<form data-controller="form-with-trix" data-action="trix-change->form#disableSubmitIfTrixAttachmentsUploading">
<input type="submit" name="commit" value="Save File" data-form-target="submit">
</form>
基于 Hey.com 的代码。
// app/javascript/controllers/form_with_trix_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ['submit']
disableSubmitIfTrixAttachmentsUploading(/*event*/) {
const { hasTrixAttachmentsUploading } = this
this.submitTargets.forEach(submitTarget => submitTarget.disabled = hasTrixAttachmentsUploading)
}
get hasTrixAttachmentsUploading() {
return this.trixAttachments.some(attachment => attachment.isPending())
}
get trixAttachments() {
return this.trixElements.flatMap(trix => trix.editor.getDocument().getAttachments())
}
get trixElements() {
return Array.from(this.element.querySelectorAll("trix-editor"))
}
}
形式:
<%= form_with(model: @my_model,
data: {
controller: "form-with-trix",
action: "trix-change->form-with-trix#disableSubmitIfTrixAttachmentsUploading"
}) do |form| %>
...
<%= form.submit "Submit", data: { form_with_trix_target: "submit" } %>
<% end %>