冠军

思胜.NET 高级培训

导航

公告

统计

2010年8月1日 #

jQuery 原理的模拟代码 -2 数据部分

 在 jQuery 中,可以对每一个 DOM 对象保存私有的数据。

 

这个数据当然要通过属性来进行存取,但是,有多个属性怎么办呢?,要定义多个属性吗?,属性的名字叫什么呢?会不会与其他的属性有冲突呢?

 

在 jQuery 中,针对 DOM  对象扩展的私有数据可以用一个对象来表示,多个数据就使用这个对象的多个属性来表示。为了能够通过 DOM 对象找到这个扩展数据对象,而不会与其他现有的属性冲突,在 jQuery 中通过 expando 这个常量表示扩展对象的属性名,这个 expando 的值是计算出来的。而这个属性的值就是用来找到扩展对象的键值。

 

例如,我们可以定义 expando 的值为 "jQuery1234" ,那么,我们可以为每个 DOM 对象增加这个名为  "jQuery1234" 的属性,这个属性的值可以是一个键,例如为 1000。

 

在 jQuery 对象上的 cache 用来保存所有对象扩展的对象,这个对象可以看作一个字典,属性名就是键值,所对应的值就是扩展数据对象。

 

也就是说,在 jQuery 对象的 cache 上,将会有一个 1000 的成员,这个成员引用的对象就是 1000 号 DOM 对象的私有扩展对象。1000 号成员的私有数据将被存在在这个对象上。

 

当一个 DOM 对象需要取得扩展数据的时候,首先通过对象的 expando 属性取得一个键值,然后通过这个键值到 jQuery.cache 中取得自己的扩展对象,然后在扩展对象上读写数据。

 

  1 /// <reference path="jQuery-core.js" />
  2 
  3 // 常用方法
  4 function now() {
  5     return (new Date).getTime();
  6 }
  7 
  8 // 扩充数据的属性名,动态生成,避免与已有的属性冲突
  9 var expando = "jQuery" + now(), uuid = 0, windowData = {};
 10 jQuery.cache = {};
 11 jQuery.expando = expando;
 12 
 13 // 数据管理,可以针对 DOM 对象保存私有的数据,可以读取保存的数据
 14 jQuery.fn.data = function (key, value) {
 15 
 16     // 读取
 17     if (value === undefined) {
 18         return jQuery.data(this[0], key);
 19     }
 20     else {  // 设置
 21 
 22         this.each(
 23                     function () {
 24                         jQuery.data(this, key, value);
 25                     }
 26                     );
 27     }
 28 }
 29 // 移除数据,删除保存在对象上的数据
 30 jQuery.fn.removeData = function (key) {
 31     return this.each(function () {
 32         jQuery.removeData(this, key);
 33     })
 34 }
 35 
 36 
 37 // 为元素保存数据
 38 jQuery.data = function (elem, name, data) {     // #1001
 39 
 40     // 取得元素保存数据的键值
 41     var id = elem[expando], cache = jQuery.cache, thisCache;
 42 
 43     // 没有 id 的情况下,无法取值
 44     if (!id && typeof name === "string" && data === undefined) {
 45         return null;
 46     }
 47 
 48     // Compute a unique ID for the element
 49     // 为元素计算一个唯一的键值
 50     if (!id) {
 51         id = ++uuid;
 52     }
 53 
 54     // 如果没有保存过
 55     if (!cache[id]) {
 56         elem[expando] = id;     // 在元素上保存键值
 57         cache[id] = {};         // 在 cache 上创建一个对象保存元素对应的值
 58     }
 59 
 60     // 取得此元素的数据对象
 61     thisCache = cache[id];
 62 
 63     // Prevent overriding the named cache with undefined values
 64     // 保存值
 65     if (data !== undefined) {
 66         thisCache[name] = data;
 67     }
 68 
 69     // 返回对应的值
 70     return typeof name === "string" ? thisCache[name] : thisCache;
 71 
 72 }
 73 
 74 // 删除保存的数据
 75 jQuery.removeData = function (elem, name) {     // #1042
 76 
 77     var id = elem[expando], cache = jQuery.cache, thisCache = cache[id];
 78 
 79     // If we want to remove a specific section of the element's data
 80     if (name) {
 81         if (thisCache) {
 82             // Remove the section of cache data
 83             delete thisCache[name];
 84 
 85             // If we've removed all the data, remove the element's cache
 86             if (jQuery.isEmptyObject(thisCache)) {
 87                 jQuery.removeData(elem);
 88             }
 89         }
 90 
 91         // Otherwise, we want to remove all of the element's data
 92     } else {
 93 
 94         delete elem[jQuery.expando];
 95 
 96         // Completely remove the data cache
 97         delete cache[id];
 98     }
 99 }
100 
101 // 检查对象是否是空的
102 jQuery.isEmptyObject = function (obj) {
103     // 遍历元素的属性,只有要属性就返回假,否则返回真
104     for (var name in obj) {
105         return false;
106     }
107     return true;
108 
109 }
110 
111 // toString 是 jQuery 中定义的一个变量 #68
112 // hasOwnProperty                    #69
113 
114 // 检查是否是一个函数
115 jQuery.isFunction = function (obj) {
116     return toString.call(obj) === "[object Function]";
117 }
118 
119 // 检查是否为一个数组
120 jQuery.isArray = function( obj ) {
121         return toString.call(obj) === "[object Array]";
122     }
123 
124 // 是否是纯粹的 js 对象,而不是 DOM 对象,或者 window 对象
125 jQuery.isPlainObject = function( obj ) {
126         // Must be an Object.
127         // Because of IE, we also have to check the presence of the constructor property.
128         // Make sure that DOM nodes and window objects don't pass through, as well
129         if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) {
130             return false;
131         }
132         
133         // Not own constructor property must be Object
134         if ( obj.constructor
135             && !hasOwnProperty.call(obj, "constructor")
136             && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) {
137             return false;
138         }
139         
140         // Own properties are enumerated firstly, so to speed up,
141         // if last one is own, then all properties are own.
142     
143         var key;
144         for ( key in obj ) {}
145         
146         return key === undefined || hasOwnProperty.call( obj, key );
147     }
148 

 

 

 

下面的脚本可以保存或者读取对象的扩展数据。

 

1 // 数据操作
2 $("#msg").data("name""Hello, world.");
3 alert($("#msg").data("name"));
4 $("#msg").removeData("name");
5 alert($("#msg").data("name"));

 

 jQuery 原理的模拟代码 -0 目录

 

posted @ 2010-08-01 08:56 冠军 阅读(1552) 评论(2) 编辑

jQuery 原理的模拟代码 -1 核心部分

 

最近又看了一下 jQuery 1.4.2, 为了便于理解,将 jQuery 的核心使用比较简单的代码模拟一下。方便学习。

 

核心部分实现了两种选择器,使用 id 和标记名,还可以提供 css 的设置,以及 text 的设置。

 

  1 // # 表示在 jQuery 1.4.2 中对应的行数
  2 
  3 // 定义变量 undefined 方便使用
  4 var undefined = undefined;
  5 
  6 // jQuery 是一个函数,其实调用 jQuery.fn.init 创建对象
  7 var $ = jQuery = window.$ = window.jQuery               // #19
  8             = function (selector, context) {
  9                 return new jQuery.fn.init(selector, context);
 10             },
 11 
 12 // 定义 toString 变量引用 Object 原型的 toString
 13 toString = Object.prototype.toString,
 14 
 15 // 用来检查是否是一个 id
 16 idExpr = /^#([\w-]+)$/;
 17 
 18 // 设置 jQuery 的原型对象, 用于所有 jQuery 对象共享
 19 jQuery.fn = jQuery.prototype = {                        // #74
 20 
 21     length: 0,                                          // #190
 22 
 23     jquery: "1.4.2",                                    // # 187
 24 
 25     // 这是一个示例,仅仅提供两种选择方式:id 和标记名
 26     init: function (selector, context) {                // #75
 27 
 28         // Handle HTML strings
 29         if (typeof selector === "string") {
 30             // Are we dealing with HTML string or an ID?
 31             match = idExpr.exec(selector);
 32 
 33             // Verify a match, and that no context was specified for #id
 34             if (match && match[1]) {
 35                 var elem = document.getElementById(match[1]);
 36                 if (elem) {
 37                     this.length = 1;
 38                     this[0= elem;
 39                 }
 40             }
 41             else {
 42                 // 直接使用标记名
 43                 var nodes = document.getElementsByTagName(selector);
 44                 for (var l = nodes.length, j = 0; j < l; j++) {
 45                     this[j] = nodes[j];
 46                 }
 47                 this.length = nodes.length;
 48             }
 49 
 50             this.context = document;
 51             this.selector = selector;
 52 
 53             return this;
 54         }
 55     },
 56 
 57     // 代表的 DOM 对象的个数
 58     size: function () {                                 // #193
 59         return this.length;
 60     },
 61 
 62     // 用来设置 css 样式
 63     css: function (name, value) {                       // #4564
 64         this.each(
 65                     function (name, value) {
 66                         this.style[name] = value;
 67                     },
 68                     arguments       // 实际的参数以数组的形式传递
 69                     );
 70         return this;
 71     },
 72 
 73     // 用来设置文本内容
 74     text: function (val) {                              // #3995
 75         if (val) {
 76             this.each(function () {
 77                 this.innerHTML = val;
 78             },
 79                     arguments       // 实际的参数以数组的形式传递
 80                     )
 81         }
 82         return this;
 83     },
 84 
 85     // 用来对所有的 DOM 对象进行操作
 86     // callback 自定义的回调函数
 87     // args 自定义的参数
 88     each: function (callback, args) {                   // #244
 89         return jQuery.each(this, callback, args);
 90     }
 91 
 92 }
 93 
 94 // init 函数的原型也就是 jQuery 的原型
 95 jQuery.fn.init.prototype = jQuery.prototype;            // #303
 96 
 97 // 用来遍历 jQuery 对象中包含的元素
 98 jQuery.each = function (object, callback, args) {       // #550
 99 
100     var i = 0, length = object.length;
101 
102     // 没有提供参数
103     if (args === undefined) {
104 
105         for (var value = object[0];
106                     i < length && callback.call(value, i, value) !== false;
107                      value = object[++i])
108         { }
109     }
110 
111     else {
112         for (; i < length; ) {
113             if (callback.apply(object[i++], args) === false) {
114                 break;
115             }
116         }
117     }
118 }
119 

在 jQuery 中, jQuery 对象实际上是一个仿数组的对象,代表通过选择器得到的所有 DOM 对象的集合,它像数组一样有 length 属性,表示代表的 DOM 对象的个数,还可以通过下标进行遍历。

 

95 行的 jQuery.each 是 jQuery 中用来遍历这个仿数组,对其中的每个元素进行遍历处理的基本方法,callback 表示处理这个 DOM 对象的函数。通常情况下,我们并不使用这个方法,而是使用 jQuery 对象的 each 方法进行遍历。jQuery 对象的 css 和 text 方法在内部实际上使用 jQuery 对象的 each 方法对所选择的元素进行处理。

 

这些函数及对象的关系见:jQuery 原型关系图

 

下面的脚本使用这个脚本库。

 

1  // 原型操作
2  $("h1").text("Hello, world.").css("color""green");
3 

 

  jQuery 原理的模拟代码 -0 目录

posted @ 2010-08-01 00:03 冠军 阅读(2161) 评论(3) 编辑