Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

attr-types

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

attr-types

Convert simple types to and from HTML node attributes

  • 1.0.2
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
34
increased by112.5%
Maintainers
1
Weekly downloads
 
Created
Source

Attr Types

Build Status

Convert simple types to and from HTML node attributes. This is useful when building WebComponents.

Note that this only allows simple types (as opposed to complex types), which are typically used in HTML attributes. See this on how to pass complex data to WebComponents.

Parsing

import AttrTypes from 'attr-types';

AttrTypes.string('asdf')   // => 'asdf'
AttrTypes.number('3')      // => 3
AttrTypes.array('w,a,s,d') // => ['w', 'a', 's', 'd']
AttrTypes.bool('')         // => true
AttrTypes.bool(null)       // => false

const aOfN = AttrTypes.arrayOf(number);
aOfN('1,2,3') // => [1, 2, 3]
aOfN('1,2,c') // => null

const lOrR = AttrTypes.oneOf(['left', 'right']);
AttrTypes.lOrR('left') // => 'left'
AttrTypes.lOrR('down') // => null

Stringifying

import AttrTypes from 'attr-types';

AttrTypes.number.stringify(3) // => '3'
AttrTypes.array.stringify(['w', 'a', 's', 'd']) // => 'w,a,s,d'
AttrTypes.bool.stringify(true) // => ''
AttrTypes.bool.stringify(false) // => null

const aOfN = AttrTypes.arrayOf(number);
aOfN.stringify([1, 2, 3]) // => '1,2,3'

const lOrR = AttrTypes.oneOf(['left', 'right']);
lOrR.stringify('left') // => 'left'
lOrR.stringify('down') // => null


DOM Interaction

To get the value of an attribute (e.g. inside attributeChangedCallback):

// You need to remember the type
const attrType = getTypeFor(attrName);
const value = attrType(el.getAttribute(attrName));

To reflect a changed property in the node attributes, use:

// You need to remember the type
const attrType = getTypeFor(attrName);

const attr = attrType.stringify(value);

if (attr == null) {
  el.removeAttribute(attrName);
} else {
  el.setAttribute(attrName, attr);
}

AttrTypes is used in the wild by hy-drawer and hy-push-state.

FAQs

Package last updated on 31 Aug 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc