-
Notifications
You must be signed in to change notification settings - Fork 165
/
dataset.js
57 lines (49 loc) · 1.45 KB
/
dataset.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
(function () {
var forEach = [].forEach,
regex = /^data-(.+)/,
dashChar = /\-([a-z])/ig,
el = document.createElement('div'),
mutationSupported = false,
match
;
function detectMutation() {
mutationSupported = true;
this.removeEventListener('DOMAttrModified', detectMutation, false);
}
function toCamelCase(s) {
return s.replace(dashChar, function (m,l) { return l.toUpperCase(); });
}
function updateDataset() {
var dataset = {};
forEach.call(this.attributes, function(attr) {
if (match = attr.name.match(regex))
dataset[toCamelCase(match[1])] = attr.value;
});
return dataset;
}
// only add support if the browser doesn't support data-* natively
if (el.dataset != undefined) return;
el.addEventListener('DOMAttrModified', detectMutation, false);
el.setAttribute('foo', 'bar');
function defineElementGetter (obj, prop, getter) {
if (Object.defineProperty) {
Object.defineProperty(obj, prop,{
get : getter
});
} else {
obj.__defineGetter__(prop, getter);
}
}
defineElementGetter(Element.prototype, 'dataset', mutationSupported
? function () {
if (!this._datasetCache) {
this._datasetCache = updateDataset.call(this);
}
return this._datasetCache;
}
: updateDataset
);
document.addEventListener('DOMAttrModified', function (event) {
delete event.target._datasetCache;
}, false);
})();