可排序

在此示例中,我们展示了如何将 可排序 javascript 库与 htmx 集成。

¥In this example we show how to integrate the Sortable javascript library with htmx.

首先,我们使用 Sortable javascript 库初始化 .sortable 类:

¥To begin we initialize the .sortable class with the Sortable javascript library:

htmx.onLoad(function(content) {
    var sortables = content.querySelectorAll(".sortable");
    for (var i = 0; i < sortables.length; i++) {
      var sortable = sortables[i];
      var sortableInstance = new Sortable(sortable, {
          animation: 150,
          ghostClass: 'blue-background-class',

          // Make the `.htmx-indicator` unsortable
          filter: ".htmx-indicator",
          onMove: function (evt) {
            return evt.related.className.indexOf('htmx-indicator') === -1;
          },

          // Disable sorting on the `end` event
          onEnd: function (evt) {
            this.option("disabled", true);
          }
      });

      // Re-enable sorting on the `htmx:afterSwap` event
      sortable.addEventListener("htmx:afterSwap", function() {
        sortableInstance.option("disabled", false);
      });
    }
})

接下来,我们创建一个包含一些可排序 div 的表单,并在 end 事件上触发一个 ajax 请求,由 Sortable.js 触发:

¥Next, we create a form that has some sortable divs within it, and we trigger an ajax request on the end event, fired by Sortable.js:

<form class="sortable" hx-post="/items" hx-trigger="end">
  <div class="htmx-indicator">Updating...</div>
  <div><input type='hidden' name='item' value='1'/>Item 1</div>
  <div><input type='hidden' name='item' value='2'/>Item 2</div>
  <div><input type='hidden' name='item' value='3'/>Item 3</div>
  <div><input type='hidden' name='item' value='4'/>Item 4</div>
  <div><input type='hidden' name='item' value='5'/>Item 5</div>
</form>

请注意,每个 div 内部都有一个隐藏的输入,用于指定该行的项目 ID。

¥Note that each div has a hidden input inside of it that specifies the item id for that row.

当通过 Sortable.js 拖放重新排序列表时,将触发 end 事件。htmx 随后将以新顺序将项目 ID 发布到 /items,以便由服务器持久保存。

¥When the list is reordered via the Sortable.js drag-and-drop, the end event will be fired. htmx will then post the item ids in the new order to /items, to be persisted by the server.

就是这样!

¥That’s it!

Server Requests ↑ Show

🔗Demo