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>
Class
:
2. Create a javascript // 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>'
}
}
DataComponent
instance
3. Register you class into a after register all components that you want, call run
method.
new DataComponent([Article]).run();