【问题标题】:Rails Turbo doesn't trigger turbo:load eventRails Turbo 不会触发 turbo:load 事件
【发布时间】:2023-01-08 06:09:23
【问题描述】:

turbo:load 事件不会在 turbo 访问后触发(正如 documentation 所说的那样)。它在初始整页加载后按预期工作。我可以捕捉到“turbo:before-fetch-response”事件,但我对 turbo:load、:render、:frame-render、:frame-load 没有运气。

我的 turbo_stream 请求格式为 TURBO_STREAM 以销毁附件。控制器响应是

respond_to do |format|
  format.turbo_stream do
    render 'attachments/delete_document',
               locals: { target: "docs-list-#{img.id}" }
  end
end

我将返回两个 turbo-streams,它们的更新和删除操作按预期工作:

<turbo-stream action="remove" target="<%= target %>">
  <template></template>
</turbo-stream>

<turbo-stream action="update" target="flash_messages">
<template>
  <%= render partial: 'layouts/flash', formats: :html,
             locals: { type: :notice,
                       message: 'Attachment removed.' } %>
</template>
</turbo-stream>

(注意:这是另一个post 的问题。那里提出的解决方案在我的情况下不起作用,因为完整的属性只存在于HTML img elements。) (我在 Rails 7.0.1 中使用@hotwired/turbo@^7.1.0、@hotwired/turbo-rails@^7.1.1)

【问题讨论】:

    标签: ruby-on-rails hotwire-rails turbo turbo-rails hotwire


    【解决方案1】:

    我已经通过 turbo:render 事件解决了这个问题:

    document.addEventListener('DOMContentLoaded', startFrontController)
    document.addEventListener('turbo:render', startFrontController)
    
    function startFrontController(event) {
      document.removeEventListener('DOMContentLoaded', startFrontController)
      new FrontController().start()
    }
    

    请参阅 Turbo 事件文档:https://turbo.hotwired.dev/reference/events

    【讨论】:

      【解决方案2】:

      与 Sergio 的回答类似,我最终使用了 turbo 提供的事件之一——在我的案例中是 turbo:before-fetch-response,因为大多数其他事件都没有触发。仍然不确定为什么。

      然而: 我发现最好的答案是使用 Stimulus。提供用于添加 javascript 功能的简洁界面。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-02
        • 1970-01-01
        • 1970-01-01
        • 2014-09-18
        • 2015-06-25
        • 2014-11-30
        • 2012-06-12
        • 1970-01-01
        相关资源
        最近更新 更多