jQuery UI 的 sortable 是實作拖曳排序最強大的元件,但它琳瑯滿目的參數常讓人眼花撩亂。本文系統性地整理它的回呼參數、常用設定、事件與方法,並附上把排序結果存進資料庫的實作。
所有回呼都會收到 event 與 ui 兩個參數,其中 ui 常用屬性包括:ui.helper(拖曳輔助元素,通常是克隆體)、ui.position(游標相對位置)、ui.offset(游標相對頁面位置)、ui.item(當前拖曳元素)、ui.placeholder(占位符)與 ui.sender(來源 sortable 物件)。
start(開始)、sort(排序中)、change(座標改變)、beforeStop(結束前)、stop(結束)、update(結束且座標已變),以及跨清單的 receive、over、out、activate、deactivate。
destroy(移除拖動)、disable / enable(停用/啟用)、option(讀寫參數)、serialize 與 toArray(序列化 id)、refresh / refreshPositions(重算)、cancel(取消本次排序)。
排序結果的保存有兩種常見做法:寫入 cookie 或存進資料庫。以下示範以三欄版型為例,在 stop 事件中收集各欄順序並以 Ajax 送出(註:作者提到 update 可能執行兩次較耗資源,因此改用 stop,但 stop 在順序未變時也會觸發,需依情境取捨)。
$(function() {
var show = $(".loader");
var listleft = $("div[id='column_left']");
var listcenter = $("div[id='column_center']");
var listright = $("div[id='column_right']");
$(".column").sortable({
opacity: 0.5,
revert: true,
cursor: 'move',
connectWith: ".column",
stop: function(){
var left = [], center = [], right = [];
listleft.children(".portlet").each(function(){ left.push(this.title); });
listcenter.children(".portlet").each(function(){ center.push(this.title); });
listright.children(".portlet").each(function(){ right.push(this.title); });
$.ajax({
type: "post",
url: jsonUrl,
data: { leftid: left.join(','), centerid: center.join(','), rightid: right.join(',') },
success: function(msg){ show.html(""); }
});
}
});
});
掌握這些參數與事件後,幾乎所有拖曳排序的情境都能迎刃而過。