0

I have this UI class with a closeSideMenu function. The event listener below calls it, but the only problem is that it is logged as undefined in the console.

class UI {
  constructor() {
    this.sideMenu = document.querySelector('.nav-items-sidebar .menu');
  }

  closeSideMenu() {
    console.log(this.sideMenu);
  }
}

ui = new UI();

document.querySelector('.nav-items-sidebar .toggler').addEventListener('mouseup', ui.closeSideMenu);
console.log(document.querySelector('.nav-items-sidebar .toggler'));

function closeSideMenuClicked() {
  ui.closeSideMenu();
}

I have a separate project with the same format that works here:

class UI {
  constructor() {
    this.post = document.querySelector('#posts');
    this.titleInput = document.querySelector('#title');
    this.bodyInput = document.querySelector('#body');
    this.idInput = document.querySelector('#id');
    this.postSubmit = document.querySelector('.post-submit');
    this.forState = 'add';
  }
  clearFields() {
    this.titleInput.value = '';
    this.bodyInput.value = '';
  }
}
Storm Llamas
  • 119
  • 1
  • 2
  • 10
  • 1
    Your function `ui.closeSideMenu` is called by the `window`, so you `this` will refer to the window inside your `closeSideMenu` method (which doesn't have the sideMenu` property). If you use the function `closeSideMenuClicked` you won't get your error – Nick Parsons Jan 17 '20 at 01:14
  • Got it. Really meant to call ```closeSideMenuClicked``` Thanks a bunch. – Storm Llamas Jan 17 '20 at 01:42

0 Answers0