Skip to content

Instantly share code, notes, and snippets.

@selbekk
Last active March 30, 2018 18:52
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save selbekk/1bdcff3aec5ea2aa744a to your computer and use it in GitHub Desktop.
A simple rewrite of Elijah Grey's dataset polyfill to ES2015. Works with babel!
/*
@name HTML 5 dataset Support
@version 0.0.2
@home http://code.eligrey.com/html5/dataset/
@author Elijah Grey - eligrey.com
@license http://www.gnu.org/licenses/lgpl.html
Rewritten to ES2015 by Kristofer Selbekk
*/
Element.prototype.setDataAttribute = function(name, value) {
return value !== undefined ? this.setAttribute('data-' + name, value) : this.removeDataAttribute(name);
};
Element.prototype.removeDataAttribute = function(name) {
return this.removeAttribute('data-' + name);
};
Element.prototype.setDataAttributes = function(items) {
if ( items instanceof Object ) {
for (var attr in items) if ( items.hasOwnProperty(attr) ) this.setDataAttribute(attr, items[attr]);
}
};
if ( !Element.prototype.__lookupGetter__("dataset") ) {
Element.prototype.__defineGetter__("dataset", () => {
function lambda(o) { return () => o }
function dataSetterFunc(ref_el, attrName) { return val => ref_el.setDataAttribute(attrName, val); }
let HTML5_DOMStringMap;
try { // simulate DOMStringMap w/accessor support
const getter_test = {};
getter_test.__defineGetter__("test", () => {}); // test setting accessor on normal object
HTML5_DOMStringMap = {};
} catch(e) { HTML5_DOMStringMap = document.createElement("div") } // use a DOM object for IE8
[...this.attributes].forEach(attr => {
if ( this.attributes.hasOwnProperty(attr) && this.attributes[attr].name && /^data-[a-z_\-\d]*$/i.test(this.attributes[attr].name) ) {
const attrName = this.attributes[attr].name.substr(5);
const attrVal = this.attributes[attr].value;
try {
HTML5_DOMStringMap.__defineGetter__(attrName, lambda(attrVal || '') );
HTML5_DOMStringMap.__defineSetter__(attrName, dataSetterFunc(this, attrName) );
}
catch (e) { HTML5_DOMStringMap[attrName] = attrVal } // if accessors are not working
}
});
return HTML5_DOMStringMap;
});
}
export default {};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment