forked from madrobby/zepto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.js
106 lines (98 loc) · 2.87 KB
/
data.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Zepto.js
// (c) 2010-2015 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
// The following code is heavily inspired by jQuery's $.fn.data()
(function($){
var data = {},
dataAttr = $.fn.data,
camelize = $.camelCase,
exp = $.expando = 'Zepto' + (+new Date()),
emptyArray = [];
// Get value from node:
// 1. first try key as given,
// 2. then try camelized key,
// 3. fall back to reading "data-*" attribute.
function getData(node, name) {
var id = node[exp],
store = id && data[id];
if (name === undefined) {
return store || setData(node);
} else {
if (store) {
if (name in store) {
return store[name];
}
var camelName = camelize(name);
if (camelName in store) {
return store[camelName];
}
}
return dataAttr.call($(node), name);
}
}
// Store value under camelized key on node
function setData(node, name, value) {
//给node增加一个属性exp
var id = node[exp] || (node[exp] = ++$.uuid),
store = data[id] || (data[id] = attributeData(node));
if (name !== undefined) {
store[camelize(name)] = value;
}
return store;
}
// Read all "data-*" attributes from a node
function attributeData(node) {
var store = {};
$.each(node.attributes || emptyArray, function(i, attr){
if (attr.name.indexOf('data-') == 0) {
store[camelize(attr.name.replace('data-', ''))] =
$.zepto.deserializeValue(attr.value);//将value还原
}
});
return store;
}
$.fn.data = function(name, value) {
return value === undefined ?
// set multiple values via object
$.isPlainObject(name) ?
this.each(function(i, node){
$.each(name, function(key, value){
setData(node, key, value);
});
}) :
// get value from first element
(0 in this ? getData(this[0], name) : undefined) :
// set value on all elements
this.each(function(){
setData(this, name, value);
});
};
$.fn.removeData = function(names) {
if (typeof names == 'string') {
names = names.split(/\s+/);
}
return this.each(function(){
var id = this[exp], store = id && data[id];
if (store) {
$.each(names || store, function(key){
delete store[names ? camelize(this) : key];
});
}
})
}
// Generate extended `remove` and `empty` functions
//重写remove empty
;['remove', 'empty'].forEach(function(methodName){
var origFn = $.fn[methodName];
$.fn[methodName] = function() {
//找出所有节点
var elements = this.find('*');
//remove的话再加上自身
if (methodName === 'remove') {
elements = elements.add(this);
}
elements.removeData();
return origFn.call(this);
}
})
})(Zepto);