做者:zhangl
原文:jQuey之Callbacks实现javascript
jQuery.myCallbacks = function () {
// 这里主要是options参数为'once;memory;once memory'
// 获取options
var options = arguments[0] || '';
// 搜集fire被调用时,传入的参数
var arg = [];
// 搜集add传入的函数
var list = [];
// 判断cb是否调用过fire
var isFired = false;
// 当前fire调用的函数索引
var fireIndex = 0;
function fire() {
// 循环执行add添加的函数
for (; fireIndex < list.length; fireIndex++) {
list[fireIndex].apply(window, arg);
}
// 若是options是once,清空list数组
if (options.indexOf('once') !== -1) {
list.length = 0;
fireIndex = 0;
}
}
return {
add: function (func) {
list.push(func);
// options为memory而且fire被调用用过
if (options.indexOf('memory') !== -1 && isFired) {
fire();
}
return this;
},
fire: function () {
arg = arguments;
isFired = true;
fireIndex = 0;
fire();
}
};
};
复制代码
jQuery.myDeferred = function () {
var arrCallbacks = [
[jQuery.Callbacks('once memory'), 'done', 'resolve'],
[jQuery.Callbacks('once memory'), 'fail', 'reject'],
[jQuery.Callbacks('memory'), 'progress', 'notify']
];
var deferred = {};
// 是不是pending状态
var isPending = true;
for (var i = 0; i < arrCallbacks.length; i++) {
// deferred绑定done, fial, progress API
deferred[arrCallbacks[i][1]] = (function (index) {
return function (func) {
arrCallbacks[i][0].add(func);
}
})(i);
// deferred绑定resolve, reject, notify API
deferred[arrCallbacks[i][2]] = (function (index) {
return function () {
if (isPending) {
arrCallbacks[i][0].fire.apply(window, arguments);
arrCallbacks[i][2] === 'resolve' || arrCallbacks[i][2] === 'reject' ? isPending = false : '';
}
}
})(i);
}
return deferred;
};
复制代码