extract-data-options

0.0.1 • Public • Published

extract-data-options

Build Status npm version js-standard-style

Sauce Test Status

Extract options from data attributes:

<div class="js-carousel"
     data-carousel-index="0"
     data-carousel-auto-play="true"
     data-carousel-controls.prev=".js-prev"
     data-carousel-controls.next=".js-next"
     data-carousel-dots=".my-dots">
</div>
// Import the module
var extractDataOptions = require('extract-data-options')
 
// Get the element
var element = document.querySelector('.js-carousel')
 
// Extract the options from `data-carousel-*` attributes
var options = extractDataOptions(element, 'carousel')

The function will return:

{
  index: 0,
  autoPlay: true,
  controls: {
    prev: '.js-prev',
    next: '.js-next'
  },
  dots: '.my-dots'
}

installation

npm install extract-data-options --save

usage

function

extractDataOptions(element: HTMLElement, namespace: String) : Object

If you don't pass a namespace, it will return all data-* options.

camel case

This module will automatically convert the attributes names into camelCase. So, an attribute like data-example-my-option will be turned into myOption.

nested properties

You can use nested properties too. Just use a dot (.) to define the keypath:

data-example-prop.show.example="hello", will result into:

{
  prop: {
    show: {
      example: 'hello'
    }
  }
}

OBS: Don't worry about this notation with dots. It is a valid HTML5 standard.

json

This module will always attempt to parse the values as JSON, otherwise it will set the value as a String.

The following options:

<div data-option-boolean="true"
     data-option-number="3.14"
     data-option-object='{"key": "value"}'
     data-option-array="[1, 2, 3]"
     data-option-string="A simple string">
</div>

Will produce the result below:

{
  boolean: true,
  number: 3.14,
  object: {key: 'value'},
  array: [1, 2, 3],
  string: 'A simple string'
}

tests

Install all dependencies:

npm install

Run the tests:

npm test

license

MIT

Package Sidebar

Install

npm i extract-data-options

Weekly Downloads

2

Version

0.0.1

License

MIT

Last publish

Collaborators

  • gsantiago