Skip to content

Instantly share code, notes, and snippets.

@AshHeskes
Forked from dsheiko/package.json
Last active February 19, 2016 18:08
Show Gist options
  • Save AshHeskes/138893b038d2b6ad6994 to your computer and use it in GitHub Desktop.
Save AshHeskes/138893b038d2b6ad6994 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 ].name;
if ( attr.indexOf( "data-" ) === 0 ) {
datakey = _attrToDataKey( attr );
_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