jquery事件绑定解绑机制源码解析


Posted in Javascript onSeptember 19, 2016

引子

为什么Jquery能实现不传回调函数也能解绑事件?如下:

$("p").on("click",function(){
  alert("The paragraph was clicked.");
});

$("#box1").off("click");

事件绑定解绑机制

调用on函数的时候,将生成一份事件数据,结构如下:

{
  type: type,
  origType: origType,
  data: data,
  handler: handler,
  guid: guid,
  selector: selector,
  needsContext: needsContext,
  namespace: namespace
}

并将该数据加入到元素的缓存中。jquery中每个元素都可以有一个缓存(只有有需要的时候才生成),其实就是该元素的一个属性。jquery为每个元素的每种事件都建立一个队列,用来保存事件处理函数,所以可以对一个元素添加多个事件处理函数。缓存的结构如下:

"div#box":{ //元素
  "Jquery623873":{ //元素的缓存
    "events":{ 
      "click":[
       {  //元素click事件的事件数据
             type: type,
             origType: origType,
             data: data,
             handler: handler,
             guid: guid,
             selector: selector,
             needsContext: needsContext,
             namespace: namespace
               }
      ],
      "mousemove":[
       {
             type: type,
             origType: origType,
             data: data,
             handler: handler,
             guid: guid,
             selector: selector,
             needsContext: needsContext,
             namespace: namespace
               }
      ]
    }
  }
}

当要解绑事件的时候,如果没指定fn参数,jquery就会从该元素的缓存里拿到要解绑的事件的处理函数队列,从里面拿出fn参数,然后调用removeEventListener进行解绑。

源代码

代码注释可能不太清楚,可以复制出来看

jquery原型中的on,one,off方法:

事件绑定从这里开始

jQuery.fn.extend( {

  on: function( types, selector, data, fn ) {
    return on( this, types, selector, data, fn );
  },
  one: function( types, selector, data, fn ) {
    return on( this, types, selector, data, fn, 1 );
  },
  off: function( types, selector, fn ) {

    //此处省略处理参数的代码

    return this.each( function() {
      jQuery.event.remove( this, types, fn, selector );
    } );
  }
} );

独立出来供one和on调用的on函数:

function on( elem, types, selector, data, fn, one ) {
  var origFn, type;

  //此处省略处理参数的代码

  //是否是通过one绑定,是的话使用一个函数代理当前事件回调函数,代理函数只执行一次
  //这里使用到了代理模式
  if ( one === 1 ) {   
    origFn = fn;
    fn = function( event ) {

      // Can use an empty set, since event contains the info
      jQuery().off( event );
      return origFn.apply( this, arguments );
    };

    // Use same guid so caller can remove using origFn
    fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
  }

  /************************************************
  *** jquery将所有选择到的元素到放到一个数组里,然后
  *** 对每个元素到使用event对象的add方法绑定事件
  *************************************************/
  return elem.each( function() {
    jQuery.event.add( this, types, fn, data, selector );
  } );
}

处理参数的代码也可以看一下,实现on("click",function(){})这样调用 on:function(types, selector, data, fn)也不会出错。其实就是内部判断,如果data, fn参数为空的时候,把selector赋给fn 

event对象是事件绑定的一个关键对象:

这里处理把事件绑定到元素和把事件信息添加到元素缓存的工作:

jQuery.event = {

  add: function( elem, types, handler, data, selector ) {

    var handleObjIn, eventHandle, tmp,
      events, t, handleObj,
      special, handlers, type, namespaces, origType,
      elemData = dataPriv.get( elem );  //这句将检查elem是否被缓存,如果没有将会创建一个缓存添加到elem元素上。形式诸如:elem["jQuery310057655476080253721"] = {}


    // Don't attach events to noData or text/comment nodes (but allow plain objects)
    if ( !elemData ) {
      return;
    }


    //用户可以传入一个自定义数据对象来代替事件回调函数,将事件回调函数放在这个数据对象的handler属性里
    if ( handler.handler ) {
      handleObjIn = handler;
      handler = handleObjIn.handler;
      selector = handleObjIn.selector;
    }

    //每个事件回调函数都会生成一个唯一的id,以后find/remove的时候会用到

    if ( !handler.guid ) {
      handler.guid = jQuery.guid++;
    }

    // 如果元素第一次绑定事件,则初始化元素的事件数据结构和主回调函数(main)
    //说明:每个元素有一个主回调函数,作为绑定多个事件到该元素时的回调的入口
    if ( !( events = elemData.events ) ) {
      events = elemData.events = {};
    }
    //这里就是初始化主回调函数的代码
    if ( !( eventHandle = elemData.handle ) ) {
      eventHandle = elemData.handle = function( e ) {

        // Discard the second event of a jQuery.event.trigger() and
        // when an event is called after a page has unloaded
        return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
          jQuery.event.dispatch.apply( elem, arguments ) : undefined;
      };
    }

    // 处理事件绑定,考虑到可能会通过空格分隔传入多个事件,这里要进行多事件处理
    types = ( types || "" ).match( rnotwhite ) || [ "" ];
    t = types.length;
    while ( t-- ) {
      tmp = rtypenamespace.exec( types[ t ] ) || []; 
      type = origType = tmp[ 1 ];
      namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();

      // There *must* be a type, no attaching namespace-only handlers
      if ( !type ) {
        continue;
      }

      // If event changes its type, use the special event handlers for the changed type
      special = jQuery.event.special[ type ] || {};

      // If selector defined, determine special event api type, otherwise given type
      type = ( selector ? special.delegateType : special.bindType ) || type;

      // Update special based on newly reset type
      special = jQuery.event.special[ type ] || {};

      // 事件回调函数的数据对象
      handleObj = jQuery.extend( {
        type: type,
        origType: origType,
        data: data,
        handler: handler,
        guid: handler.guid,
        selector: selector,
        needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
        namespace: namespaces.join( "." )
      }, handleObjIn );

      // 加入第一次绑定该类事件,会初始化一个数组作为事件回调函数队列,每个元素的每一种事件有一个队列
      if ( !( handlers = events[ type ] ) ) {
        handlers = events[ type ] = [];
        handlers.delegateCount = 0;

        // Only use addEventListener if the special events handler returns false
        if ( !special.setup ||
          special.setup.call( elem, data, namespaces, eventHandle ) === false ) {

          if ( elem.addEventListener ) {
            elem.addEventListener( type, eventHandle );
          }
        }
      }

      if ( special.add ) {
        special.add.call( elem, handleObj );

        if ( !handleObj.handler.guid ) {
          handleObj.handler.guid = handler.guid;
        }
      }

      // 加入到事件回调函数队列
      if ( selector ) {
        handlers.splice( handlers.delegateCount++, 0, handleObj );
      } else {
        handlers.push( handleObj );
      }

      // Keep track of which events have ever been used, for event optimization
      // 用来追踪哪些事件从未被使用,用以优化
      jQuery.event.global[ type ] = true;
    }

  }
};

千万注意,对象和数组传的是引用!比如将事件数据保存到缓存的代码:

handlers = events[ type ] = [];

if ( selector ) {
  handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
  handlers.push( handleObj );
}

handlers的改变,events[ type ]会同时改变。

dataPriv就是管理缓存的对象:

其工作就是给元素创建一个属性,这个属性是一个对象,然后把与这个元素相关的信息放到这个对象里面,缓存起来。这样需要使用到这个对象的信息时,只要知道这个对象就可以拿到:

function Data() {
  this.expando = jQuery.expando + Data.uid++;
}

Data.uid = 1;

//删除部分没用到代码
Data.prototype = {

  cache: function( owner ) {

    // 取出缓存,可见缓存就是目标对象的一个属性
    var value = owner[ this.expando ];

    // 如果对象还没有缓存,则创建一个
    if ( !value ) {
      value = {};

      // We can accept data for non-element nodes in modern browsers,
      // but we should not, see #8335.
      // Always return an empty object.
      if ( acceptData( owner ) ) {

        // If it is a node unlikely to be stringify-ed or looped over
        // use plain assignment
        if ( owner.nodeType ) {
          owner[ this.expando ] = value;

        // Otherwise secure it in a non-enumerable property
        // configurable must be true to allow the property to be
        // deleted when data is removed
        } else {
          Object.defineProperty( owner, this.expando, {
            value: value,
            configurable: true
          } );
        }
      }
    }

    return value;
  },
  get: function( owner, key ) {
    return key === undefined ?
      this.cache( owner ) :

      // Always use camelCase key (gh-2257) 驼峰命名
      owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ];
  },
  remove: function( owner, key ) {
    var i,
      cache = owner[ this.expando ];

    if ( cache === undefined ) {
      return;
    }

    if ( key !== undefined ) {

      // Support array or space separated string of keys
      if ( jQuery.isArray( key ) ) {

        // If key is an array of keys...
        // We always set camelCase keys, so remove that.
        key = key.map( jQuery.camelCase );
      } else {
        key = jQuery.camelCase( key );

        // If a key with the spaces exists, use it.
        // Otherwise, create an array by matching non-whitespace
        key = key in cache ?
          [ key ] :
          ( key.match( rnotwhite ) || [] );
      }

      i = key.length;

      while ( i-- ) {
        delete cache[ key[ i ] ];
      }
    }

    // Remove the expando if there's no more data
    if ( key === undefined || jQuery.isEmptyObject( cache ) ) {

      // Support: Chrome <=35 - 45
      // Webkit & Blink performance suffers when deleting properties
      // from DOM nodes, so set to undefined instead
      // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
      if ( owner.nodeType ) {
        owner[ this.expando ] = undefined;
      } else {
        delete owner[ this.expando ];
      }
    }
  },
  hasData: function( owner ) {
    var cache = owner[ this.expando ];
    return cache !== undefined && !jQuery.isEmptyObject( cache );
  }
};

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
javascript 动态生成私有变量访问器
Dec 06 Javascript
js获得地址栏?问号后参数的方法
Aug 08 Javascript
JavaScript实现简单的时钟实例代码
Nov 23 Javascript
深入浅出理解javaScript原型链
May 09 Javascript
JS中dom0级事件和dom2级事件的区别介绍
May 05 Javascript
关于动态生成dom绑定事件失效的原因及解决方法
Aug 06 Javascript
bootstrap laydate日期组件使用详解
Jan 04 Javascript
vue axios 给生产环境和发布环境配置不同的接口地址(推荐)
May 08 Javascript
详解如何在Vue项目中导出Excel
Apr 19 Javascript
jQuery三组基本动画与自定义动画操作实例总结
May 09 jQuery
(开源)微信小程序+mqtt,esp8266温湿度读取
Apr 02 Javascript
VUE递归树形实现多级列表
Jul 15 Vue.js
JavaScript学习笔记整理_setTimeout的应用
Sep 19 #Javascript
Node.js + Redis Sorted Set实现任务队列
Sep 19 #Javascript
JavaScript学习笔记整理_用于模式匹配的String方法
Sep 19 #Javascript
JavaScript学习笔记整理_简单实现枚举类型,扑克牌应用
Sep 19 #Javascript
JavaScript学习笔记整理_关于表达式和语句
Sep 19 #Javascript
javascript学习笔记_浅谈基础语法,类型,变量
Sep 19 #Javascript
js中用cssText设置css样式的简单方法
Sep 19 #Javascript
You might like
Zend Framework中的简单工厂模式 图文
2012/07/10 PHP
PHP写的资源下载防盗链类分享
2014/05/12 PHP
php实现在线通讯录功能(附源码)
2016/05/13 PHP
php实现给二维数组中所有一维数组添加值的方法
2017/02/04 PHP
PHP简单实现二维数组赋值与遍历功能示例
2017/10/19 PHP
Javascript Object.extend
2010/05/18 Javascript
复制网页内容,粘贴之后自动加上网址的实现方法(脚本之家特别整理)
2014/10/16 Javascript
js中style.display=&quot;&quot;无效的解决方法
2014/10/30 Javascript
JavaScript中Cookie操作实例
2015/01/09 Javascript
JavaScript监听文本框回车事件并过滤文本框空格的方法
2015/04/16 Javascript
JS判断字符串字节数并截取长度的方法
2016/03/05 Javascript
BootStrap与validator 使用笔记(JAVA SpringMVC实现)
2016/09/21 Javascript
js中数组的常用方法小结
2016/12/30 Javascript
20行js代码实现的贪吃蛇小游戏
2017/06/20 Javascript
JS小球抛物线轨迹运动的两种实现方法详解
2017/12/20 Javascript
node.js中express模块创建服务器和http模块客户端发请求
2019/03/06 Javascript
vue倒计时刷新页面不会从头开始的解决方法
2020/03/03 Javascript
openlayers实现图标拖动获取坐标
2020/09/25 Javascript
教你如何在Django 1.6中正确使用 Signal
2014/06/22 Python
python实现的简单窗口倒计时界面实例
2015/05/05 Python
Python切片工具pillow用法示例
2018/03/30 Python
python实现旋转和水平翻转的方法
2018/10/25 Python
在Python中pandas.DataFrame重置索引名称的实例
2018/11/06 Python
python画图系列之个性化显示x轴区段文字的实例
2018/12/13 Python
python五子棋游戏的设计与实现
2019/06/18 Python
Python的log日志功能及设置方法
2019/07/11 Python
Anaconda的安装与虚拟环境建立
2020/11/18 Python
python定义具名元组实例操作
2021/02/28 Python
考研复习计划
2015/01/19 职场文书
2015年安置帮教工作总结
2015/05/22 职场文书
HTML中table表格拆分合并(colspan、rowspan)
2021/04/07 HTML / CSS
MySQL 视图(View)原理解析
2021/05/19 MySQL
React如何创建组件
2021/06/27 Javascript
DIY胆机必读:各国电子管评价
2022/04/06 无线电
Java多线程并发FutureTask使用详解
2022/06/28 Java/Android
python读取mat文件生成h5文件的实现
2022/07/15 Python