Skip to content

Add $(el).data() (#94)#313

Open
fabien-michel wants to merge 1 commit intoHubSpot:devfrom
fabien-michel:data
Open

Add $(el).data() (#94)#313
fabien-michel wants to merge 1 commit intoHubSpot:devfrom
fabien-michel:data

Conversation

@fabien-michel
Copy link
Copy Markdown

No description provided.

Copy link
Copy Markdown
Contributor

@Abbondanzo Abbondanzo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One minor nit. The suggestion I provided will only work in modern browsers since Object.entries is not supported by ie11 without polyfill

// get single value
el.dataset.foo;
// set single value
el.dataset.bar = { value: 42 };
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JQuery performs serialization with data attributes, so we'll want to stringify/parse these values. Otherwise, they get written as [object Object]. Something like this should work

function data(el, key, value) {
  // Return the full dataset
  if (key === undefined) {
    const toReturn = {};
    for (const [dKey, dValue] of Object.entries(el.dataset)) {
      try {
        toReturn[dKey] = JSON.parse(dValue);
      } catch (_) {
        // Do nothing
      }
    }
    return toReturn;
  }
  // "key" is a string, either get or set
  else if (typeof key === "string") {
    if (value === undefined) {
      try {
        return JSON.parse(el.dataset[key]);
      } catch (_) {
        return undefined;
      }
    } else {
      el.dataset[key] = JSON.stringify(value);
    }
  }
  // "key" can be any object, writes each key to dataset
  else if (key && typeof key === "object") {
    for (const [dKey, dValue] of Object.entries(key)) {
      el.dataset[dKey] = JSON.stringify(dValue);
    }
  }
}

// get all data-* values
data(el);
// get single value
data(el, "foo");
// set single value
data(el, "bar", { value: 42 });

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants