Skip to content

Instantly share code, notes, and snippets.

@dsheiko
Last active January 30, 2019 11:53
Show Gist options
  • Save dsheiko/37e4673cce20d5896510 to your computer and use it in GitHub Desktop.
Save dsheiko/37e4673cce20d5896510 to your computer and use it in GitHub Desktop.
jsdom Element.dataset partial polyfill
{
"name": "jsdomdataset",
"version": "1.0.0",
"description": "",
"main": "polyfill-jsdom.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "GPL-3.0",
"dependencies": {
"jsdom": "^7.0.2"
}
}
/**
* Convert data-attr into key
* data-foo-bar -> fooBar
* @param {String} val
* @returns {String}
*/
var _attrToDataKey = function( val ){
var out = val.substr( 5 );
return out.split( "-" ).map(function( part, inx ){
if ( !inx ) {
return part;
}
return part.charAt( 0 ).toUpperCase() + part.substr( 1 );
}).join( "" );
},
/**
* Produce dataset object emulating behavior of el.dataset
* @param {Element} el
* @returns {Object}
*/
_getNodeDataAttrs = function( el ){
var i = 0,
atts = el.attributes,
len = atts.length,
attr,
_datasetMap = [],
// represents el.dataset
proxy = {},
datakey;
for ( ; i < len; i++ ){
attr = atts[ i ].nodeName;
if ( attr.indexOf( "data-" ) === 0 ) {
datakey = _attrToDataKey( attr );
if ( typeof _datasetMap[ datakey ] !== "undefined" ) {
break;
}
_datasetMap[ datakey ] = atts[ i ].nodeValue;
(function( datakey ){
// every data-attr found on the element makes a getter and setter
Object.defineProperty( proxy, datakey, {
enumerable: true,
configurable: true,
get: function() {
return _datasetMap[ datakey ];
},
set: function ( val ) {
_datasetMap[ datakey ] = val;
el.setAttribute( attr, val );
}
});
}( datakey ));
}
}
return proxy;
};
Object.defineProperty( global.window.Element.prototype, "dataset", {
get: function() {
return _getNodeDataAttrs( this );
}
});
require( "jsdom" ).env({
html: "<html><body data-bind=\"foo\" data-foo-bar=\"baz\"></body></html>",
done: function ( err, window ) {
var el = window.document.body;
global.window = window;
require( "./polyfill-jsdom" );
console.log( "Access: ", el.dataset.bind === "foo" ? "OK" : "FAIL" );
el.dataset.bind = "bar";
console.log( "Mutation: ", el.dataset.bind === "bar" ? "OK" : "FAIL" );
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment