Accessing SortableJS instance from Stimulus controller in Action Cable channel

81 views Asked by At

I'm using Stimulus and SortableJS in a Rails application to handle drag-and-drop functionality. In my Stimulus controller, I've created a SortableJS instance named sortableInstance. I need to access this instance in my Action Cable channel when the order is updated.

Stimulus Controller (/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 Cable Channel (/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?
  },
});

I tried storing the const sortableInstace in SessionStorage. Can't work because circular structures can't be JSON.stringified. I don't mind if the solution isn't beautiful, I'm not even sure if it's possible anyways.

0

There are 0 answers