Last active
August 5, 2018 21:12
-
-
Save JimBobSquarePants/1c2beb65977d995659ea46366f39cdd2 to your computer and use it in GitHub Desktop.
API for getting data from an elements data-attributes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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