Home > Mobile >  How do I make a class that can create a HTML element with an onclick attribute which can call method
How do I make a class that can create a HTML element with an onclick attribute which can call method

Time:08-05

I am building a shopping cart where I want to add items to the cart. When a items is created it has a quantity increment and decrement button. And becuase I want to handle everything cart related inside the cart class, I want to be able to call a method of the cart class from the button's onclick. How can I achieve this?

const myElm = document.getElementById("myElm");

class Cart {

  constructor(myElm) {
    myElm.innerHTML = `
      <button type="button" onclick="this.doSomething('hello world')">CLICK ME</button>
    `;
  }

  doSomething(x) {
    console.log(x);
  }

}

const myCart = new Cart(myElm);
<div id="myElm"></div>

CodePudding user response:

Use addEventListener to properly bind events, and keep in mind the scope of this:

const myElm = document.getElementById("myElm");

class Cart {

  constructor(myElm) {
    let btn = document.createElement('button');
    btn.innerHTML = 'CLICK ME';
    btn.addEventListener('click', () => {
      // here "this" is a reference to the Cart class, since we're using an arrow function
      this.doSomething('hello world');
    })
    myElm.append(btn);
  }

  doSomething(x) {
    console.log(x);
  }

}

const myCart = new Cart(myElm);
<div id="myElm"></div>

  • Related