javascript Rails 7 - Active Storage和Filepond

6ju8rftf  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(121)

所以我有一个Orders的表单页面,我使用Active Storage实现了文件上传,还使用importmapjavascript实现了名为Filepond的拖放功能
但是,当我使用rails s启动rails服务器并导航到表单页面时,Filepond不会出现(拖放功能)x1c 0d1x
现在,当我刷新页面时,它会加载Filepond

现在,当我再次导航到其他页面并返回到表单时,文件不会加载

app/javascript/application.js

// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
import "bootstrap"
import "custom/custom"
import "filepond"
import "filepond-plugin-image-preview"

app/javascript/custom/custom.js

// Import FilePond
import * as FilePond from 'filepond';

// Import the plugin code
import FilePondPluginImagePreview from 'filepond-plugin-image-preview';

// Register the plugin
FilePond.registerPlugin(FilePondPluginImagePreview);

// Get a reference to the file input element
const inputElement = document.querySelector('#files-upload');

// Create a FilePond instance
const pond = FilePond.create(inputElement, {
    credits: {},
    storeAsFile: true,
    allowMultiple: true,
    allowReorder: true,
});

views/orders/_form.html.erb

<%= form_with(model: order) do |f| %>
 .......
 .......
 <%= f.file_field :files, multiple: true, direct_upload: true, 
 required: true, id:"files-upload" %>
 ........
 ........
<% end %>

结论:

每次导航到表单页面时,都必须刷新页面一次,以便filepond's drag n drop feature能够工作
那么有没有办法在rails 7中修复这个问题,这样我们就不需要刷新页面就可以让filepond工作了??

c0vxltue

c0vxltue1#

好了,我知道问题所在了,问题出在JavaScript上,由于Rails 7使用Turbo来处理JavaScript,我们需要使用Turbo Hotwire提供的Event "turbo:load"

  • turbo:load在初始页面加载后触发一次,并在每次访问Turbo后再次触发。使用event.detail.timing对象访问访问计时指标。

来源:https://turbo.hotwired.dev/reference/events
custom.js

// Import FilePond
import * as FilePond from 'filepond';

// Import the plugin code
import FilePondPluginImagePreview from 'filepond-plugin-image-preview';

// Register the plugin
FilePond.registerPlugin(FilePondPluginImagePreview);

document.addEventListener("turbo:load", loadFilePond);

function loadFilePond(){
    // Get a reference to the file input element
    const inputElement = document.querySelector('#files-upload');

    // Create a FilePond instance
    const pond = FilePond.create(inputElement, {
        credits: {},
        storeAsFile: true,
        allowMultiple: true,
        allowReorder: true,
    });
}

相关问题