简体   繁体   中英

Rails Turbo doesn't trigger turbo:load event

The turbo:load event is not fired after a turbo visit (as the documentation says it should). It works as expected after the initial full-page load. I can catch the "turbo:before-fetch-response" event, but I have no luck with turbo:load, :render, :frame-render, :frame-load.

My turbo_stream request is format TURBO_STREAM to destroy an attachment. The controller response is

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

and I'm returning two turbo-streams whose update and remove actions work as intended:

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

(Note: This is a bump of another post . The solution proposed there doesn't work in my case as the complete attribute only exists for HTML img elements .) (I'm using @hotwired/turbo@^7.1.0, @hotwired/turbo-rails@^7.1.1 in Rails 7.0.1)

I had resolve that problem with turbo:render event:

document.addEventListener('DOMContentLoaded', startFrontController)
document.addEventListener('turbo:render', startFrontController)

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

See Turbo events documentation: https://turbo.hotwired.dev/reference/events

Similar to Sergio's answer, I ended up using one of the turbo-provided events - turbo:before-fetch-response in my case, since most other events didn't fire. Still not sure why.

However: I found that the best answer is to use Stimulus. Provides a clean interface for adding javascript functionality.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM