I want to create a dynamic HTML/JS user interface. For this I will dynamically create objects, which will be represented as a button on my html. now, I want to track click events of course. How do I dynamically add an addEventlistener to this special instance of the button? (each button creates its own svg icon) My idea is, that the object IS the button, but I am not sure how to do that...
my idea is like following:
class Lightbulb {
/**
*
* @param {String} id
* @param {boolean} state
*/
constructor(id, state){
this.id = id;
this.state = state;
/*
create the icon here...
*/
//is it somehow possible to achieve the following?
this.addEventlistener("click", this.setState(!this.state));
}
/**
*
* {boolean} newState
*/
setState(newState){
console.log(newState)
}
``
Real credit to @Guerric P
I'd never heard of Web Components (in this context) until today. And I've got to say, I whipped up an example based on your code, and the documentation Guerric P provided. Your code was actually really close. I cleaned it up a bit, but it's nearly identical to yours.
Not only does your idea have solid thought behind it, it's actually an HTML5 technology waiting to be implemented.
class Lightbulb extends HTMLElement {
state = false;
/**
* @param {String} id
*/
constructor(id) {
super();
this.id = id;
this.addEventListener("click", this.toggleState);
}
toggleState() {
this.state = !this.state;
this.classList.toggle("on", this.state);
}
}
customElements.define("light-bulb", Lightbulb);
light-bulb.on {
background-color: yellow;
}
<light-bulb>Clickable Lightbulb</light-bulb>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With