rails7刺激和数据塔两次初始化

发布于 2025-01-24 00:39:21 字数 1043 浏览 3 评论 0原文

当我在刺激控制器中准备数据表时,它会发射两倍的涡轮行为(用于缓存目的),因此,

当我尝试在Rails6中使用Fix时,我会在没有刺激的情况下使用修复时两次初始化它的数据,如果我放置不起作用,

document.addEventListener('turbo:before-cache', function() {
     if ($('#invoices_wrapper').length ==1) {invoicetable.destroy() ;} });

如果我放在Console.log在该功能中,我发现它甚至没有执行。 如何使用刺激正确设置数据表?

这是我的代码

import { Controller } from "@hotwired/stimulus"
import $ from 'jquery';

import 'jszip';
import datatable from 'datatables.net-bs5';
import 'datatables.net-buttons-bs5';

window.datatable = datatable();

export default class extends Controller {
  connect() {

      var invoicetable = $('#invoices').DataTable({
      
      'order': [1, 'asc'],
      'serverSide': true,
      "processing": true,
      'ajax' : '/invoices.json',
      columns: [
      //{data: 'id', searchable: false, orderable: false},
        {data: 'name' },
        {data: 'value' }        
      ],
      initComplete: function ()
            {
             console.log("done")
        }
    });
  }
}

When I prepare DataTable in stimulus controller, it fires twice what is behaviour of turbo (for caching purposes) and therefore I get DataTables error of initializing it twice

When I tried fix as I use in rails6 without stimulus, it does not work

document.addEventListener('turbo:before-cache', function() {
     if ($('#invoices_wrapper').length ==1) {invoicetable.destroy() ;} });

If I put console.log inside that function, I see it is not even executed.
How can I properly setup DataTables with stimulus?

This is my code

import { Controller } from "@hotwired/stimulus"
import $ from 'jquery';

import 'jszip';
import datatable from 'datatables.net-bs5';
import 'datatables.net-buttons-bs5';

window.datatable = datatable();

export default class extends Controller {
  connect() {

      var invoicetable = $('#invoices').DataTable({
      
      'order': [1, 'asc'],
      'serverSide': true,
      "processing": true,
      'ajax' : '/invoices.json',
      columns: [
      //{data: 'id', searchable: false, orderable: false},
        {data: 'name' },
        {data: 'value' }        
      ],
      initComplete: function ()
            {
             console.log("done")
        }
    });
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文