Turbo Frames 无法从头部识别 Javascript

Turbo Frames not recognizing Javascript from the head

提问人:Patrick Vellia 提问时间:9/3/2022 更新时间:9/3/2022 访问量:464

问:

我正在努力构建我的模板并完成初始步骤。我在 Rails 7.0.2.4、turbo-rails 1.1.1、Bootstrap 5 上。

在我的布局模板中,我有以下内容:

= javascript_include_tag "application", data:{turbo:{track: "reload"}}, defer: true

链接到我的应用程序/javascript/application.js,这里的相关部分是:

import * as bootstrap from "bootstrap"

var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl)
})

上面的第二部分启用了 Bootstraps 工具提示。

回到我的模板中,我将其分解为三个 Turbo Frames:

%turbo-frame{id: "main_frame", data:{turbo:{action: "advance"}}}
    .container-fluid
        .row.flex-nowrap
            .col-auto.col-md-3.col-xl-2.px-sm-2.px-0.bg-dark
                %turbo-frame{id: "sidebar", data:{turbo:{action: "advance"}}}
            .col
                %turbo-frame{id: "content", data:{turbo:{action: "advance"}}}
                    = yield

首先是main_frame,然后分为侧边栏和内容框架。单击侧边栏中具有 date-turbo-frame: “content” 属性的链接,会将 Content 框架替换为必要的内容。

现在,在大多数完整的内容框架上,该框架的顶部有一个导航标题,该标题在左右两侧有一个按钮,中间有一个文本:

%turbo-frame{id: "content", data:{turbo:{action: "advance"}}}
    .row
        .d-flex
            .p-2
                %a{href: path, data:{turbo:{frame: "content"}, 
                  bs:{toggle: "tooltip", placement: "bottom", 
                    title: "Back"}}, 
                  aria:{label: "Back"}}
                    %i.bi.bi-arrow-left-circle-fill{aria:{hidden: "true"}}
            .flex-grow-1
                // Some Text
            .p-2
                %a{href: new_path, data:{turbo:{frame: "new"}, 
                  bs:{toggle: "tooltip", placement: "bottom", 
                    title: "New"}}, 
                  aria:{label: "New"}}
                    %i.bi.bi-plus{aria:{hidden: "true"}}

当您导航到此替换的内容时,工具提示不起作用。但是,当您通过浏览器重新加载整个页面时,工具提示会突然起作用,因为代码在头部。

有没有办法让框架加载必要的 Javascript?

Ruby-on-Rails 推特引导 涡轮增压

评论


答:

2赞 Maxence 9/3/2022 #1

基本上,使用 Turbo,您的 JS 被添加到头部,而不是在页面加载时进行修改。

所以当你打电话时:

var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))

基本上,它会在将 JS 附加到应用程序的确切时间在 DOM 中搜索请求的 DOM 节点。如果您的应用刷新了 turbo Frame,则不会播放它。请看我最近回复的这个线程: 如何使用 Turbo、ImportMaps 和 Stimulus 在 Rails 7 应用程序中加载特定于页面的自定义 Javascript 函数?

如果希望在加载新内容时刷新工具提示,则必须使用 Stimulus,将代码放入 Stimulus 控制器的方法中,并将该控制器附加到应用程序中可能包含工具提示的每个部分。connect()

如果您不想在应用中的许多位置附加 Stimulus 控制器,还可以将控制器附加到标记,并在方法中添加突变观察器 (https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver)。刺激的目的实际上是为了防止向突变观察者发送垃圾邮件,但如果你有很多工具提示,它仍然是一个可行的解决方案)<html>connect()javascript/application.js

评论

1赞 Patrick Vellia 9/12/2022
谢谢!这被证明是有帮助的。现在,我已经将相关的涡轮增压帧与包含此代码的数据控制器包装在一起。但是,当我稍后重构时,将其放在带有 Mutation Observer 的 html 选项卡中会更有效(因为我对 Mutation Observer 的理解还不够,无法使用它)。