question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Add suport to datasets

See original GitHub issue

Support to element datasets.

Adding this code allows dataset support:

before(function (next) {
    if (global.window && !options.skipWindowCheck) {
      throw new Error(
        'mocha-jsdom: already a browser environment, or mocha-jsdom invoked ' +
        "twice. use 'skipWindowCheck' to disable this check.")
    }

    require('jsdom').env(
      extend(extend({}, options), { done: done }))

    function done (errors, window) {
      if (options.globalize) {
        propagateToGlobal(window)
      } else {
        global.window = window
      }

      if (options.console) {
        window.console = global.console
      }

      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( "" );
      },
      _datasetProxy = null,
      _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() {
          _datasetProxy = _datasetProxy || _getNodeDataAttrs( this );
          return _datasetProxy;
        }
      });

      if (errors) {
        return next(getError(errors))
      }

      next(null)
    }
  })

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
colbycheezecommented, Mar 26, 2016

I couldn’t get this to work properly. It seemed to be buggy when there were multiple dom elements with the same data key but a different value. (it just gave everything the same value based on the first one it found)

I just decided to rewrite it and clean it up. Now i just use this after attaching new html to the dom.

const dashToCamel = name => name.replace(/-([a-z])/g, g => g[1].toUpperCase());
const getDataFrom = element => (
  Object.assign({}, ... [... element.attributes]
    .filter(attr => attr.nodeName.indexOf('data-') === 0)
    .map(attr => ({
      [dashToCamel(attr.nodeName.slice(5))]: attr.nodeValue,
    }))
  )
);

const polyfillDataset = (rootElement = document.body) => {
  rootElement.dataset = getDataFrom(rootElement); // eslint-disable-line no-param-reassign
  [... rootElement.children].forEach((child) => {
    polyfillDataset(child);
  });
};

export default polyfillDataset;

in the test file:

import polyfillDataset from 'polyfillDataset';


const theBody = `
  <ul data-arbitrary="thing">
    <li data-order="1"> list content </li>
    <li data-order="2"> list content </li>
    <li data-order="3"> list content </li>
  </ul>
`;
document.body.innerHTML = theBody;
polyfillDataset();

now everything works. Before all of the ‘data-order’ values would be 1, AND all of the li attributes would also for some reason contain data-arbitrary=“thing”

0reactions
shercommented, Jan 14, 2016

Latest version doesn’t expose nodeName on attributes. Use name instead.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Working with datasets - Zendesk help
Zendesk Support datasets. The following datasets can be used to produce reports based on your tickets, and support data: Tickets: Report key ticket...
Read more >
Add Geomap Support to Datasets - SAP Help Portal
Open your dataset. Select (Geo Enrichment) in the toolbar, and then choose either of the following options: By Coordinates if you want to...
Read more >
There are 23 support datasets available on data.world.
There are 23 support datasets available on data.world. Find open data about support contributed by thousands of users and organizations across the world....
Read more >
Add support for text datasets · Issue #1128 - GitHub
Hello! I would like to suggest adding support for text datasets, for NLP. As I am planning to implement and use some of...
Read more >
Add support for the nested datasets - DevExpress
ClientDatasets is EXTREMLY important for developers who rely on DataSnap. Like the name suggests, a nested dataset is a dataset within a ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found