data-componentdeprecated

automatically instantiate components on the DOM with data-component="name" attribute.

Usage no npm install needed!

<script type="module">
  import dataComponent from 'https://cdn.skypack.dev/data-component';
</script>

README

data-component

automatically search on the DOM for components that match with you javascript classes and instantiate it.

Why

I'm tired of apply a document.querySelectorAll and for each component on the DOM, instantiate a new class manually, like this:

[...document.querySelectorAll('[data-my-component]')].forEach($element => new MyComponent($element));

It's seems ok for one case, but as you component library grows, its turn out a messy.

How to use

Consider the follow case for and Article component:

1. Declare your components on the DOM

  <article data-component="Article">...</article>

2. Create a javascript Class:

// Your class name should match with the DOM data-component="_NAME_" selector;
Class Article {
  // The first parameter on your constructor will be the DOM Element
  constructor($article) {
    this.$article = $article;
  }

 // Declare your build method to anything you like:
  build() {
    this.$article.innerHTML = '<p>Hello world!</p>'
  }
}

3. Register you class into a DataComponent instance

after register all components that you want, call run method.

  new DataComponent([Article]).run();