forked from remy/polyfills
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset.js
47 lines (40 loc) · 1.23 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
(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');
Element.prototype.__defineGetter__('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);
})();