资讯专栏INFORMATION COLUMN

jQuery 源码系列(八)data 缓存机制

shinezejian / 526人阅读

摘要:的缓存机制来看看中提高的数据缓存机制,有两个函数,分别是和,可以看出来,一个是在对象上,一个是在生成的对象上。而且从源码来看,的缓存机制自带清内存操作,更是锦上添花呀。参考源码分析数据缓存本文在上的源码地址,欢迎来。

欢迎来我的专栏查看系列文章。

不打算介绍 deferred,或者放到后面以后去介绍,因为我对于 js 的异步存在着恐惧,看了半天代码,发现,用挺好用的,一看源码,全傻眼了。如果你感兴趣,这边链接1,链接2。

数据缓存

jQuery 最初以便捷 DOM 操作而流行,而 DOM 的本质其实就是对象,开发者们又习惯性的将一些标志直接扔给 DOM 本事,这会带来内存泄漏的问题。

比如对于斐波那契数列,方法可以有递归,有迭代,如果用 js 来写的话有一个比较有意思的方法,就是用缓存来实现:

</>复制代码

  1. function fib(n){
  2. if(n == 1 || n == 0)
  3. return n;
  4. if(!fib[n-1]){
  5. fib[n-1] = fib(n-1);
  6. }
  7. if(!fib[n-2]){
  8. fib[n-2] = fib(n-2);
  9. }
  10. return fib[n-1] + fib[n-2];
  11. }

因为 fib 不仅是函数,而且是对象,JS 中万物都是对象,所以才有了这种缓存的解决办法,这就是前面所说的,不过是在 DOM 上实现的。

当然这种方法也会有弊端,造成内存泄漏。现代的浏览器有自动回收内存的机制,但当出现循环引用或闭包的时候,就会产生内存泄漏问题

就不深入去讨论了。

jQuery 的缓存机制

来看看 jQuery 中提高的数据缓存机制,有两个函数,分别是 jQuery.data()jQuery.fn.data(),可以看出来,一个是在 jQuery 对象上,一个是在 jQuery 生成的对象上。如果仔细阅读的话,你会发现 jQuery 中很多函数都有两个,原型上一个,jQuery 上一个。

jQuery.data() 有两种使用,一个用于绑定,一个用于查询:

jQuery.data( element, key, value )

jQuery.data( element, key )

上面的 element 参数表示 DOM 元素,比如一个例子如下:

</>复制代码

  1. jQuery.data(document.body, "foo", 52);
  2. jQuery.data(document.body, "bar", "test");
  3. jQuery.data(document.body, "foo"); // 52
  4. jQuery.data(document.body, "bar"); // "test"

还有 .data() 方法,.data(),这个函数就直接在 jquery 对象上实行绑定 data:

</>复制代码

  1. $("body").data("foo", 52);
  2. $("body").data("bar", { myType: "test", count: 40 });
  3. $("body").data({ baz: [ 1, 2, 3 ] });
  4. $("body").data("foo"); // 52
  5. $("body").data(); // { foo: 52, bar: { myType: "test", count: 40 }, baz: [ 1, 2, 3 ] }

这边有一个小细节数据缓存接口:

</>复制代码

  1. var jq1 = $("body");
  2. var jq2 = $("body");
  3. jq1.data("a", 1);
  4. jq2.data("a", 2);
  5. jq1.data("a"); //2
  6. jq2.data("a"); //2
  7. // 数据被覆盖
  8. $.data(jq1, "b", 3);
  9. $.data(jq2, "b", 4);
  10. $.data(jq1, "b"); //3
  11. $.data(jq2, "b"); //4
  12. // 不会被覆盖

可以看出来,通过这两种方法绑定的数据,其实是不一样的,前者会被覆盖,而后者不会,说明在 cache 中肯定有某种神秘的力量将他们区别开来

源码

在 jQuery 中的源码,大致是这样的结构:

</>复制代码

  1. function Data(){...}
  2. Data.prototype = {
  3. cache: function(){...},
  4. set: function(){...},
  5. get: function(){...},
  6. access: function(){...},
  7. remove: function(){...},
  8. hasData: function(){...}
  9. }
  10. var dataUser = new Data();
  11. jQuery.extend({
  12. data: function( elem, name, data ) {
  13. return dataUser.access( elem, name, data );
  14. },
  15. hasData: function( elem ) {
  16. return dataUser.hasData( elem ) || dataPriv.hasData( elem );
  17. },
  18. removeData: function( elem, name ) {
  19. dataUser.remove( elem, name );
  20. }
  21. })
  22. jQuery.fn.extend({
  23. data: function(){
  24. ...
  25. dataUser...
  26. ...
  27. },
  28. removeData: function(){...}
  29. })

由于之前已经弄懂 jQuery 内部结构,对于这个一点也不惊讶,在 jQuery 和 jQuery 的原型上分别有一个 data 函数,用来处理各自的情况。

既然已经知道了 data 的基本结构,我们来各个击破,先来看一下 function Data()

</>复制代码

  1. function Data() {
  2. // jQuery.expando 是 jQuery 的标识
  3. this.expando = jQuery.expando + Data.uid++;
  4. }
  5. Data.uid = 1;
  6. jQuery.expando = ("3.1.1" + Math.random()).replace( /D/g, "" )
  7. // "3.1.10.9610206515567563".replace( /D/g, "" )
  8. // "31109610206515567563"

接着是 prototype

</>复制代码

  1. Data.prototype = {
  2. // 建立一个 cache
  3. cache: function( owner ) {
  4. // Check if the owner object already has a cache
  5. var value = owner[ this.expando ];
  6. // If not, create one
  7. if ( !value ) {
  8. value = {};
  9. // We can accept data for non-element nodes in modern browsers,
  10. // but we should not, see #8335.
  11. // Always return an empty object.
  12. if ( acceptData( owner ) ) {
  13. // 判断 owner 是一个合格者后
  14. if ( owner.nodeType ) {
  15. owner[ this.expando ] = value;
  16. // Otherwise secure it in a non-enumerable property
  17. // configurable must be true to allow the property to be
  18. // deleted when data is removed
  19. } else {
  20. Object.defineProperty( owner, this.expando, {
  21. value: value,
  22. configurable: true
  23. } );
  24. }
  25. }
  26. }
  27. return value;
  28. },
  29. // set 函数就是为 dom 设置 keyvalue
  30. set: function( owner, data, value ) {
  31. var prop,
  32. cache = this.cache( owner );
  33. if ( typeof data === "string" ) {
  34. cache[ jQuery.camelCase( data ) ] = value;
  35. // 处理 data 为这种情况: [ owner, { properties } ]
  36. } else {
  37. // Copy the properties one-by-one to the cache object
  38. for ( prop in data ) {
  39. cache[ jQuery.camelCase( prop ) ] = data[ prop ];
  40. }
  41. }
  42. return cache;
  43. },
  44. get: function( owner, key ) {
  45. return key === undefined ?
  46. this.cache( owner ) :
  47. // Always use camelCase key (gh-2257)
  48. owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ];
  49. },
  50. // 用来访问,将 get、set 结合到一起,并对 underfined 判断
  51. access: function( owner, key, value ) {
  52. if ( key === undefined ||
  53. ( ( key && typeof key === "string" ) && value === undefined ) ) {
  54. return this.get( owner, key );
  55. }
  56. this.set( owner, key, value );
  57. return value !== undefined ? value : key;
  58. },
  59. // 用于移除 cache
  60. remove: function( owner, key ) {
  61. var i,
  62. cache = owner[ this.expando ];
  63. if ( cache === undefined ) {
  64. return;
  65. }
  66. if ( key !== undefined ) {
  67. // 支持删除数组格式的 key
  68. if ( jQuery.isArray( key ) ) {
  69. key = key.map( jQuery.camelCase );
  70. } else {
  71. key = jQuery.camelCase( key );
  72. // 为了保持一致,强行的构造了一个 数组
  73. key = key in cache ?
  74. [ key ] :
  75. ( key.match( rnothtmlwhite ) || [] );
  76. }
  77. i = key.length;
  78. // 删
  79. while ( i-- ) {
  80. delete cache[ key[ i ] ];
  81. }
  82. }
  83. // cache 为空的时候,删除整个缓存
  84. if ( key === undefined || jQuery.isEmptyObject( cache ) ) {
  85. if ( owner.nodeType ) {
  86. owner[ this.expando ] = undefined;
  87. } else {
  88. delete owner[ this.expando ];
  89. }
  90. }
  91. },
  92. hasData: function( owner ) {
  93. var cache = owner[ this.expando ];
  94. return cache !== undefined && !jQuery.isEmptyObject( cache );
  95. }
  96. };

然后是 jQuery.data()

</>复制代码

  1. var dataPriv = new Data(); //以后会讲到
  2. var dataUser = new Data();
  3. jQuery.extend( {
  4. hasData: function( elem ) {
  5. return dataUser.hasData( elem ) || dataPriv.hasData( elem );
  6. },
  7. data: function( elem, name, data ) {
  8. return dataUser.access( elem, name, data );
  9. },
  10. removeData: function( elem, name ) {
  11. dataUser.remove( elem, name );
  12. },
  13. // TODO: Now that all calls to _data and _removeData have been replaced
  14. // with direct calls to dataPriv methods, these can be deprecated.
  15. _data: function( elem, name, data ) {
  16. return dataPriv.access( elem, name, data );
  17. },
  18. _removeData: function( elem, name ) {
  19. dataPriv.remove( elem, name );
  20. }
  21. } );

源码里面有 dataPriv 和 dataUser,作者做了一个 TODO 标记,

接着是 jQuery.fn.data()

</>复制代码

  1. jQuery.fn.extend( {
  2. data: function( key, value ) {
  3. var i, name, data,
  4. // 将第一个 dom 赋给 elem
  5. elem = this[ 0 ],
  6. attrs = elem && elem.attributes;
  7. // key 为 underfined,表示参数空,获取全部
  8. if ( key === undefined ) {
  9. if ( this.length ) {
  10. data = dataUser.get( elem );
  11. if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
  12. i = attrs.length;
  13. while ( i-- ) {
  14. // 这里面从 dom 的 attribute 中搜索 data- 开通的属性
  15. if ( attrs[ i ] ) {
  16. name = attrs[ i ].name;
  17. if ( name.indexOf( "data-" ) === 0 ) {
  18. name = jQuery.camelCase( name.slice( 5 ) );
  19. dataAttr( elem, name, data[ name ] );
  20. }
  21. }
  22. }
  23. dataPriv.set( elem, "hasDataAttrs", true );
  24. }
  25. }
  26. return data;
  27. }
  28. // object 类型
  29. if ( typeof key === "object" ) {
  30. return this.each( function() {
  31. dataUser.set( this, key );
  32. } );
  33. }
  34. // key value 的情况,利用 access 函数
  35. return access( this, function( value ) {
  36. var data;
  37. // The calling jQuery object (element matches) is not empty
  38. // (and therefore has an element appears at this[ 0 ]) and the
  39. // `value` parameter was not undefined. An empty jQuery object
  40. // will result in `undefined` for elem = this[ 0 ] which will
  41. // throw an exception if an attempt to read a data cache is made.
  42. if ( elem && value === undefined ) {
  43. // Attempt to get data from the cache
  44. // The key will always be camelCased in Data
  45. data = dataUser.get( elem, key );
  46. if ( data !== undefined ) {
  47. return data;
  48. }
  49. // Attempt to "discover" the data in
  50. // HTML5 custom data-* attrs
  51. data = dataAttr( elem, key );
  52. if ( data !== undefined ) {
  53. return data;
  54. }
  55. // We tried really hard, but the data doesn"t exist.
  56. return;
  57. }
  58. // Set the data...
  59. this.each( function() {
  60. // We always store the camelCased key
  61. dataUser.set( this, key, value );
  62. } );
  63. }, null, value, arguments.length > 1, null, true );
  64. },
  65. removeData: function( key ) {
  66. return this.each( function() {
  67. dataUser.remove( this, key );
  68. } );
  69. }
  70. } );

data 函数略有不同,但思路也很清晰。

有几个要提一下的函数

其中,有几个函数,也来介绍一下,acceptData

</>复制代码

  1. var acceptData = function( owner ) {
  2. // Accepts only:
  3. // - Node
  4. // - Node.ELEMENT_NODE
  5. // - Node.DOCUMENT_NODE
  6. // - Object
  7. // - Any
  8. return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
  9. };

acceptData 是判断 owner 的类型,具体关于 nodeType,去看看这里吧。

jQuery.camelCase

</>复制代码

  1. jQuery.camelCase = function (string) {
  2. return string.replace(/^-ms-/, "ms-").replace(/-([a-z])/g, function (all, letter) {
  3. return letter.toUpperCase();
  4. });
  5. }

这个函数就是做了一些特殊字符串的 replace,具体有啥用,我也不是很清楚。

isEmptyObject 是判断一个 Object 是否为空的函数,挺有意思的,可以借鉴:

</>复制代码

  1. jQuery.isEmptyObject = function (obj) {
  2. var name;
  3. for (name in obj) {
  4. return false;
  5. }
  6. return true;
  7. }

dataAttr 是一个从 DOM 中搜索以 data- 开头属性的函数:

</>复制代码

  1. function dataAttr( elem, key, data ) {
  2. var name;
  3. // If nothing was found internally, try to fetch any
  4. // data from the HTML5 data-* attribute
  5. if ( data === undefined && elem.nodeType === 1 ) {
  6. name = "data-" + key.replace( /[A-Z]/g, "-$&" ).toLowerCase();
  7. // 利用 dom 自身的 get 操作
  8. data = elem.getAttribute( name );
  9. if ( typeof data === "string" ) {
  10. try {
  11. // 先看有没有
  12. data = getData( data );
  13. } catch ( e ) {}
  14. // Make sure we set the data so it isn"t changed later
  15. dataUser.set( elem, key, data );
  16. } else {
  17. data = undefined;
  18. }
  19. }
  20. return data;
  21. }
总结

jQuery 的 data 缓存从源码来看的话,真的不是很难,而且不难发现,jQuery 缓存的实质,其实就是在内部先弄一个 Object,然后和缓存体(DOM)建立一对一的联系,所有增删改查的操作,都是围绕着 jQuery 内部来的,不直接对 DOM 操作,这样就可以避免内存泄漏。而且从源码来看,jQuery 的缓存机制自带清内存操作,更是锦上添花呀。

参考

</>复制代码

  1. jQuery 2.0.3 源码分析 数据缓存

  2. jQuery.data()

本文在 github 上的源码地址,欢迎来 star。

欢迎来我的博客交流。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/81642.html

相关文章

  • jQuery之事件绑定到触发全过程及知识点补充

    摘要:十的触发机制被点击了元素本身绑定了一个事件,但是是原生事件,它是靠绑定来触发事件的。 showImg(https://segmentfault.com/img/remote/1460000019505402); 前言:最重要的还是最后的流程图,可以试着根据流程图手写实现$().on(),下篇文章会放出模拟实现的代码。 一、举例 这是A 这是C ...

    Jioby 评论0 收藏0
  • jQuery 源码系列(十四)自定义事件

    摘要:不过也有自己的一套自定义事件方案。可以和事件拿来对比,他们都是用来模拟和执行监听的事件。冒泡事件就是就是由内向外冒泡的过程,这个过程不是很复杂。参考解密事件核心自定义设计三解密事件核心模拟事件四本文在上的源码地址,欢迎来。 欢迎来我的专栏查看系列文章。 以前,我只知道,只有当对浏览器中的元素进行点击的时候,才会出发 click 事件,其它的事件也一样,需要人为的鼠标操作。 showIm...

    elliott_hu 评论0 收藏0
  • jQuery源码解析之$.queue()、$.dequeue()和jQuery.Callbacks(

    摘要:作为此时不存在,直接从数据缓存中获取并返回。作用是触发中的回调函数,的表示只让触发一次后,就需要清理,表示是将清空成空数组还是空字符。 showImg(https://segmentfault.com/img/remote/1460000019558449); 前言:queue()方法和dequeue()方法是为 jQuery 的动画服务的,目的是为了允许一系列动画函数被异步调用,但不...

    itvincent 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<