jQuery.Callbacks 是 1.7+ 引入的核心工具類,管理函數隊列執行,支持 once、memory、unique、stopOnFalse 等標志,是 Deferred (Promise 前身) 與動畫隊列 的基礎。
// 創建帶標志的回調管理器
var callbacks = $.Callbacks('once memory');
標志位:
once:回調隊列只執行一次,後續 add/fire 無效。memory:記住最近一次 fire 的參數,新 add 的函數立即用該參數執行。unique:保證同一函數只被添加一次。stopOnFalse:某回調返回 false 時停止後續執行。callbacks.add(fn1, fn2); // 添加回調 (支持數組/多參數)
callbacks.remove(fn1); // 移除特定回調
callbacks.has(fn); // 檢查是否存在
callbacks.empty(); // 清空隊列
callbacks.disable(); // 永久禁用 (add/remove/fire 失效)
callbacks.disabled(); // 檢查是否禁用
callbacks.lock(); // 鎖定 (不可 add/remove,但可 fire)
callbacks.locked(); // 檢查是否鎖定
callbacks.fire(arg1, arg2); // 執行所有回調,傳參
callbacks.fireWith(context, [args]); // 指定 this 上下文執行
callbacks.fired(); // 是否已執行過
function createCallbacks(flags) {
flags = flags || '';
var options = {
once: ~flags.indexOf('once'),
memory: ~flags.indexOf('memory'),
unique: ~flags.indexOf('unique'),
stopOnFalse: ~flags.indexOf('stopOnFalse')
};
var list = [], // 回調函數隊列
firing = false, // 正在執行標志
fired = false, // 已執行過標志
firingStart = 0, // 執行起始索引 (支持動態添加)
firingLength = 0, // 當前執行隊列長度快照
memoryArgs; // memory 模式記住的參數
var self = {
add: function() {
if (list) {
var args = Array.prototype.slice.call(arguments);
args.forEach(function(fn) {
if (typeof fn === 'function' && (!options.unique || list.indexOf(fn) < 0)) {
list.push(fn);
}
});
// memory 模式:若已 fired,立即用記住的參數執行新添加的函數
if (options.memory && fired) {
firingLength = list.length;
memoryArgs && self.fireWith(memoryArgs[0], memoryArgs[1]);
}
}
return this;
},
remove: function() {
var args = Array.prototype.slice.call(arguments);
args.forEach(function(fn) {
var idx = list.indexOf(fn);
if (idx >= 0) list.splice(idx, 1);
});
return this;
},
fireWith: function(context, args) {
if (!firing && !options.once || (options.once && !fired)) {
firing = true;
fired = true;
memoryArgs = [context, args]; // 記住參數供 memory 模式
firingLength = list.length;
for (firingStart = 0; firingStart < firingLength; firingStart++) {
if (list[firingStart].apply(context, args) === false && options.stopOnFalse) {
break;
}
}
firing = false;
if (options.once) list = []; // once 模式執行後清空
}
return this;
},
fire: function() {
return this.fireWith(this, arguments);
},
// ... has, empty, disable, disabled, lock, locked, fired 略
};
return self;
}
var cb = $.Callbacks('memory');
cb.add(function(a) { console.log('fn1:', a); });
cb.fire(1); // fn1: 1
cb.add(function(a) { console.log('fn2:', a); }); // 立即執行: fn2: 1
cb.fire(2); // fn1: 2, fn2: 2
done/fail/progress 皆基於 Callbacks ('once memory' / 'memory')。.queue() 使用 Callbacks 管理幀回調。// 簡易事件總線
class EventBus {
constructor() { this.map = new Map(); }
on(event, fn) {
if (!this.map.has(event)) this.map.set(event, []);
this.map.get(event).push(fn);
}
off(event, fn) { /* ... */ }
emit(event, ...args) {
(this.map.get(event) || []).forEach(fn => fn(...args));
}
once(event, fn) {
const wrapper = (...args) => { fn(...args); this.off(event, wrapper); };
this.on(event, wrapper);
}
}
現代項目推薦使用原生 Promise、EventTarget 或輕量事件庫 (mitt, tiny-emitter),API 更標準、體積更小。