Skip to content

Instantly share code, notes, and snippets.

@JimBobSquarePants
Last active August 5, 2018 21:12
Show Gist options
  • Save JimBobSquarePants/1c2beb65977d995659ea46366f39cdd2 to your computer and use it in GitHub Desktop.
Save JimBobSquarePants/1c2beb65977d995659ea46366f39cdd2 to your computer and use it in GitHub Desktop.
API for getting data from an elements data-attributes.
const DataGrabber = w => {
const dataMap = new WeakMap();
const rdashAlpha = /-([a-z])/g;
const fcamelCase = (all, letter) => letter.toUpperCase();
/**
* Returns a transformed string in camel case format
* @param {string} value The string to alter
* @returns {string}
* @memberof DataGrabber
*/
camelCase(value) {
const noDash = value.replace(rdashAlpha, fcamelCase);
return noDash.charAt(0).toLowerCase() + noDash.substring(1)
}
class Grabber {
/**
* Returns any data stored in data-attributes for the given element
* @param {HTMLElement} element
* @returns {object}
* @memberof Grabber
*/
getData(element) {
if (!dataMap.has(element)) {
let attr = {},
data = Object.values(element.attributes).filter(a => a.name.indexOf("data-") === 0);
data.forEach(d => {
attr[camelCase(d.name.slice(5))] = d.value;
});
dataMap.set(element, { attr: attr });
}
return dataMap.get(element);
}
}
// Create our instance...
const grabber = new Grabber();
// ... and bind to the window. If you don't want to do this delete the line below and the "w" parameter.
w.$dg = grabber.fn;
})(window);
export default DataGrabber
@JimBobSquarePants
Copy link
Author

JimBobSquarePants commented Aug 5, 2018

JQuery provides data parsing functionality that you could add to the above to store the converted type.

https://code.jquery.com/jquery-3.3.1.js

var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/;

function getData( data ) {
	if ( data === "true" ) {
		return true;
	}

	if ( data === "false" ) {
		return false;
	}

	if ( data === "null" ) {
		return null;
	}

	// Only convert to a number if it doesn't change the string
	if ( data === +data + "" ) {
		return +data;
	}

	if ( rbrace.test( data ) ) {
		return JSON.parse( data );
	}

	return data;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment