在上一篇jQuery.Callbacks之demo主要说了Callbacks对象初始化常见的选项,这一篇主要分析下Callbacks对象的源代码,对给出两个较为繁琐的demo

 // String to Object options format cache
var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache
/*
这个函数主要将传入的options字符串封装成对象
比如将传入的'once memory'封装成
optionsCache['once memory'] = {
once : true,
memory : true
}
这样方便下次同样的options复用和判断
*/
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.split( core_rspace ), function( _, flag ) {
object[ flag ] = true;
});
return object;
} /*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists)
//大多数情况下这个变量是包含两个元素的数组,[0]表示上次调用的对象,[1]表示上次调用的参数
memory,
// Flag to know if list was already fired
//标识是否执行过回调函数,主要用来实现once
fired,
// Flag to know if list is currently firing
//当前是否在firing,可以参考多线编程中锁的概念,主要用在调用回调函数时,对callbacks对象进行add、remove或者fire,后面会有两个单独的例子说明这种情况
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
//所有的回调会被push到这个数组
list = [],
// Stack of fire calls for repeatable lists
//结合firing使用,如果有once选项没什么作用,否则当firing为true时将add或者fire的操作临时存入这个变量,以便于循环完list时继续处理这个变量里面的函数队列
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
//如果设置memory为true,则将本次的参数data缓存到memory中,用于下次调用
memory = options.memory && data;
fired = true;
//如果options.memory为true,firingStart为上一次Callbacks.add后回调列表的length值
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
//如果stopOnFalse为true且本次执行的回调函数返回值为false,则终止回调函数队列的执行
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
//设置memory为false,防止调用add时会被fire(这个分支是在stopOnFalse memory时被触发)
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
//options.once为false(stack的作用见上)
if ( stack ) {
//存在递归的可能,所以不用使用while
if ( stack.length ) {
fire( stack.shift() );
}
//memory = true, memory = true的情况
} else if ( memory ) {
list = [];
} else {
//once = true, memory = false的情况
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
//实现unique(回调不唯一 或 唯一且不存在,则push)
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
//如果arg是数组,递归添加回调
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
//如果memory不是false,则直接每次add的时候都自动fire
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
//如果在执行Callbacks.remove操作的状态为firing时则更新firingLength和firingIndex的值
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
//特殊处理,如果移除的回调的索引小于当前正在执行回调的索引,则firingIdex--
//后面未执行的回调则得以正常执行
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return jQuery.inArray( fn, list ) > -1;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
}; return self;
};

  需要特殊注意的是有一个firing这个变量,下面给出这个变量的应用场景:

  1、在Callbacks.add中firing为true的情况

 // 定义三个将要增加到回调列表的回调函数fn1,fn2,fn3
function fn1(val){
console.log( 'fn1 says ' + val );
//此时Callbacks函数内部的firingLength会自动加1,虽然初始化的Callbacks对象有memory选项,
//但add并不会立即执行fn2,而是等执行完add前的函数队列之后再执行fn2
cbs.add(fn2);
}
function fn2(val){
console.log( 'fn2 says ' + val );
}
function fn3(val){
console.log( 'fn3 says ' + val );
} // Callbacks传递了memory
// 也可以这样使用$.Callbacks({ memory: true });
var cbs = $.Callbacks('memory'); // 将fn1增加到回调列表中,因为在fn1中有执行了add(fn2)操作,因此回调列表中的回调为fn1,fn2
cbs.add(fn1); //fn1 says foo
//fn2 says foo
cbs.fire('foo'); //将之前fire的参数传递给最近增加的回调fn3,并执行fn3
//fn3 says foo
cbs.add(fn3); //再执行一次fire,注意此时回调列表中的回调依次是fn1,fn2,fn3,fn2
//fn1 says bar
//fn2 says bar
//fn3 says bar
//fn2 says bar
cbs.fire('bar');

  2、在Callbacks.fireWith中firing为true的情况

function fn1(val){
console.log( 'fn1 says ' + val );
}
function fn2(val){
console.log( 'fn2 says ' + val );
//此时并不会立即触发cbs里面的回调,而是先把[window, ['bar']]放入stack里面
//等执行完fireWith前的函数队列之后才执行
cbs.fireWith(window, ['bar']);
//firingLength会减一,一定要将当前的函数remove掉,否则会导致死循环
cbs.remove(fn2);
} var cbs = $.Callbacks();
cbs.add(fn1);
cbs.add(fn2);
//fn1 says bar
//fn2 says bar
//fn1 says bar
cbs.fire('bar');

jQuery.Callbacks之源码解读的更多相关文章

  1. jQuery.data() 与 jQuery(elem).data()源码解读

    之前一直以为 jQuery(elem).data()是在内部调用了 jQuery.data(),看了代码后发现不是.但是这两个还是需要放在一起看,因为它们内部都使用了jQuery的数据缓存机制.好吧, ...

  2. 亚马逊左侧菜单延迟z三角 jquery插件jquery.menu-aim.js源码解读

    关于亚马逊的左侧菜单延迟,之前一直不知道它的实现原理.梦神提到了z三角,我也不知道这是什么东西.13号那天很有空,等领导们签字完我就可以走了.下午的时候,找到了一篇博客:http://jayuh.co ...

  3. jquery判断数据类型源码解读

    var class2type = {}; ("Boolean Number String Function Array Date RegExp Object Error").spl ...

  4. jQuery.Callbacks 源码解读二

    一.参数标记 /* * once: 确保回调列表仅只fire一次 * unique: 在执行add操作中,确保回调列表中不存在重复的回调 * stopOnFalse: 当执行回调返回值为false,则 ...

  5. 第二十五课:jQuery.event.trigger的源码解读

    本课主要来讲解jQuery.event.trigger的源码解读. trigger = function(event, data, elem, onlyHandlers){ if(elem & ...

  6. 第二十四课:jQuery.event.remove,dispatch的源码解读

    本课还是来讲解一下jQuery是如何实现它的事件系统的.这一课我们先来讲一下jQuery.event.remove的源码解读. remove方法的目的是,根据用户传参,找到事件队列,从里面把匹配的ha ...

  7. 第二十三课:jQuery.event.add的原理以及源码解读

    本课主要来讲解一下jQuery是如何实现它的事件系统的. 我们先来看一个问题: 如果有一个表格有100个tr元素,每个都要绑定mouseover/mouseout事件,改成事件代理的方式,可以节省99 ...

  8. jQuery之Deferred源码剖析

    一.前言 大约在夏季,我们谈过ES6的Promise(详见here),其实在ES6前jQuery早就有了Promise,也就是我们所知道的Deferred对象,宗旨当然也和ES6的Promise一样, ...

  9. SDWebImage源码解读之SDWebImageDownloaderOperation

    第七篇 前言 本篇文章主要讲解下载操作的相关知识,SDWebImageDownloaderOperation的主要任务是把一张图片从服务器下载到内存中.下载数据并不难,如何对下载这一系列的任务进行设计 ...

随机推荐

  1. js 更改head的title

    使用document.title = "hello"; 不能使用 $("title").text("dd");或者            $ ...

  2. 关于UID和GID的创建、修改、删除;简要举例

    用户.组和权限 安全3A资源分派 (authentication)认证 (authorization)授权 (accounting)审计 user( 用户) Linux用户:Username/UID ...

  3. make file

    CPPUTEST_USE_EXTENSIONS = Y如果没有这一句定义,CppUTestExt/MockSupport.h和CppUTestExt/MockSupport_c.h文件中的定义就不能用 ...

  4. 底部tab的返回退出和对话框

    第一种: private long exitTime = 0; @Override public boolean dispatchKeyEvent(KeyEvent event) { if (even ...

  5. java自带BASE64工具进行图片和字符串转换

    java自带BASE64工具进行图片和字符串转换 import java.io.File; import java.io.FileInputStream; import java.io.FileOut ...

  6. Linux编程下EAGAIN和EINTR宏的含义及处理

    Linux中的EAGAIN含义   在Linux环境下开发经常会碰到很多错误(设置errno),其中EAGAIN是其中比较常见的一个错误(比如用在非阻塞操作中). linux下使用write\send ...

  7. CSS线性渐变

    /*CSS线性渐变*/ FILTER: progid:DXImageTransform.Microsoft.Gradient(gradientType=0,startColorStr=#ffffff, ...

  8. nvidia 各种卡

    cudnn是针对maxwell优化的啊, maxwell下的各种卡都是游戏卡,具体可以见: https://developer.nvidia.com/maxwell-compute-architect ...

  9. Windows下MongoDB环境搭建

    MongoDB下载 登录MongoDB官网:www.mongodb.org:点击[Download MongoDB]按钮,进入如下所示界面 选择目标操作系统及其版本,比如这里选择的是64位的Windo ...

  10. Vmware /CentOS访问Windows中的文件

    1.将该文件设为共享文件夹 2.确定你的windows IP地址,用户名及密码 3.CentOS终端输入以下内容:   [root@*** mnt]# mkdir winD   [root@*** m ...