jQuery.extend({
Callbacks: function(options) {
options = typeof options === "string" ? ( optionsCache[options] || createOptions(options)) : {}; // options保存options.split后的对象 {mermory: true, stopOnFalse: true}
var memory, start, index, firing, length, testing;
var list = []; // 回调列表
// 执行回调列表
var fire = function( data ) {
memory = options.memory && data; // 获取参数值
index = start || 0; // 第一次进来直接从0开始执行回调列表,后面进来index从上一次执行完length(list.length)开始
length = list.length; // 记录上次执行的length
firing = true;
testing = true; // 如果参数有once 回调函数已经调用过了
for( ; index < length; index++) {
if(list[index].apply( data[0], data[1]) === false && options.stopOnFalse ) { // 判断执行结果是否为false,给stopOnFalse使用
break;
}
}
start = 0; // 执行完成重置start, 处理参数不传的情况,memory直接执行fire函数
firing = false;
}
// 工厂模式
var self = {
add: function() {
var startlen = list.length;
jQuery.each( arguments, function(i, value) {
if(jQuery.isFunction(value)) {
list.push(value);
}
})
if(firing) { // 执行完回调才能去获取回调函数的长度作为新起始点
start = list.length;
} else
if(memory) {
start = startlen; // add之前的回调列表函数
fire(memory); // 如果是memory,fire之后的add立即执行
}
},
fireWith: function(context, args) {
args = [ context, args ];
if(!options.once || !testing) { // 没有once || 是once,但是第一次调用
fire( args );
}
},
fire: function() {
self.fireWith( this, arguments);
return this;
}
}
return self;
}
})