sortable_controller.js 959 B

123456789101112131415161718192021222324252627282930313233343536
  1. import { Controller } from "@hotwired/stimulus";
  2. import Sortable from 'sortablejs'
  3. export default class extends Controller {
  4. connect() {
  5. this.sortable = new Sortable(this.element, {
  6. animation: 150,
  7. handle: 'tr',
  8. onEnd: this.end.bind(this),
  9. });
  10. }
  11. end(event) {
  12. let order = [];
  13. this.element.querySelectorAll('tr').forEach((row, index) => {
  14. order.push({
  15. id: row.dataset.id,
  16. position: index + 1
  17. });
  18. });
  19. fetch(this.data.get('url'), {
  20. method: 'POST',
  21. headers: {
  22. 'Content-Type': 'application/json',
  23. 'X-Requested-With': 'XMLHttpRequest'
  24. },
  25. body: JSON.stringify({order: order})
  26. }).then(Response => {
  27. if(Response.ok) {
  28. this.sortable.sort(order.map(item =>item.id))
  29. }
  30. });
  31. }
  32. }