Build Reusable Components with Native JavaScript Code
One benefit of using some JS libraies such as Vue or React is that they provide ways to building reusalble components. Here, I try to build reusalble components using natvie JS to see if can grasp the logic behind them. I use class like React.
<span id = "button1"></span> <span id = "button2"></span> <span id = "button3"></span> <script> function Counter(id){
this.el = document.getElementById(id);
this.count = 0;
this.add = function(){
this.count++;
this.el.innerHTML = `<button onclick = "${id}.add()">${this.count}</button>`;
}
this.el.innerHTML = `<button onclick = "${id}.add()">${this.count}</button>`;
} var button1 = new Counter('button1');
var button2 = new Counter('button2');
var button3 = new Counter('button3'); </script>
Here I use custom html tags like Vue.
<counter></counter> <counter></counter> <counter></counter> <script> function createCounter_20201022(){
Array.from(document.getElementsByTagName('counter')).forEach(el => {
el.innerHTML = `<button onclick = "this.innerHTML++">0</button>`
})
}
createCounter_20201022(); </script>
Reusalbe components are important not just because they are easier to to clone, but also they untanlge much logic behind data or algorithm related to those components.
Comments
Post a Comment