在操作电缆通道中从 Stimulus 控制器访问 SortableJS 实例

Accessing SortableJS instance from Stimulus controller in Action Cable channel

提问人:Fábio Lima 提问时间:11/14/2023 更新时间:11/14/2023 访问量:18

问:

我在 Rails 应用程序中使用 Stimulus 和 SortableJS 来处理拖放功能。在我的 Stimulus 控制器中,我创建了一个名为 sortableInstance 的 SortableJS 实例。当订单更新时,我需要在我的 Action Cable 频道中访问此实例。

刺激控制器 (/javascript/controllers/drag_and_drop_controller.js):

import { Controller } from "@hotwired/stimulus";
import Sortable from "sortablejs";

export default class extends Controller {
  connect() {
    // I need to access this SortableJS instance in my task_channel.js file
    const sortableInstance = Sortable.create(this.element, {

      onUpdate: (event) => {
        const taskId = event.item.dataset.taskId;
        const newPosition = event.newIndex + 1;

        // Fetch request to update task order
        fetch(`/tasks/${taskId}/reorder`, {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json",
            "X-CSRF-Token": document
              .querySelector('meta[name="csrf-token"]')
              .getAttribute("content"),
          },
          body: JSON.stringify({ new_position: newPosition }),
        })
      },
    });
  }
}

Action 有线频道 (/javascript/channels/task_channel.js):

import consumer from "./consumer";

consumer.subscriptions.create("TaskChannel", {
  received(data) {
    // How can I access the `sortableInstance` created in drag_and_drop_controller.js?
  },
});

我尝试将const sortableInstace存储在SessionStorage中。无法工作,因为循环结构不能被 JSON.stringized 化。我不介意解决方案是否不漂亮,我什至不确定它是否可行。

Ruby-on-Rails 刺激js hotwire-rails sortablejs

评论


答: 暂无答案