0

I'm working on a little web-app for my portfolio, basically it mimics the kind of system a restaurant server would use to input customer orders, calculate the totals, and "print" the bill - front end only, no backend. All that I've made so far works except one piece. I want the option to clear the whole bill upon request (suppose a huge mistake is made). I can do this in the main javascript file, but if I attempt to use the same class that is used to populate it, the object is 'undefined.'

Below is the basic structure of my class (I removed the code irrelevant to this question).

class UI{
  constructor(){
   this.billUL = document.querySelector('#bill-ul');
  }

  //succeeds, no undefined errors
  insertInBill(items){
   //get some values out of items
   //create and add items to li element
   //append li element
   this.billUL.appendChild(li);
   }

  //fails - it evaluates as undefined
  clearBill(){
   this.billUL.innerHTML = '';
  }
}

Main javascript file - this works fine:

  const billUL = document.querySelector('#bill-ul');
  clearBillBtn = document.getElementById('clear-bill')

  clearBillBtn.addEventListener('click',clearBill);

  function clearBill() {
    billUL.innerHTML = '';
    billTotal.innerText = '';
  }

Basically, I can add items correctly using a function in the class, but if I try to clear it it is undefined. My workaround is, as I said, making that clearBill() file in my main javascript file and it works.

Can anyone explain why it is undefined in the class when trying to clear but not when trying to add items indefinitely?

Bendystraw
  • 45
  • 1
  • 1
  • 4

1 Answers1

0

Because you are using clearBill passed as a reference to an event listener, at the time of execution of clearBill this inside it points to the element with the id="clear-bill", not to the instance of your class.

To fix it, simply bind(this) to the instance in the constructor:

constructor(){
  /* ... other code to run on construction time */
  // replace this.clearBill by itself, but bound to `this`
  this.clearBill = this.clearBill.bind(this);
}
connexo
  • 53,704
  • 14
  • 91
  • 128