0

I have got a class, I make a new instance of this class for two elements.

When clicked, these elements should then add a class to another element, however the console.log is displaying undefined, any ideas why?

// Wait for document to load
  window.addEventListener("DOMContentLoaded", function() {

    class menuControl {
      constructor(obj, child) {
        this.state = 0;
        this.child = child;
        this.elm = obj;
      }

      toggleActive() {
        if (this.state === 1) {
          this.state = 0; removeClass(this.child, 'toggled');
        } else {
          console.log(this.child);
          this.active = 1; addClass(this.child, 'toggled');
        }
      }

    }

    // Global Variables
    var usedcars = new menuControl(doc('usedcars__trigger'), doc('listitem__search'));
    var menu = new menuControl(doc('megamenu__trigger'), doc('megamenu'));
    function doc(id) { return document.getElementById(id); }

    (usedcars.elm).addEventListener('click', usedcars.toggleActive);

  }, false);
Martyn Ball
  • 4,679
  • 8
  • 56
  • 126
  • To get the right `this`, pass `usedcars.toggleActive.bind(usedcars)` to `addEventListener()` – Alnitak Apr 03 '17 at 14:07
  • @Alnitak so my event listener would be `(usedcars.elm).addEventListener('click', usedcars.toggleActive.bind(this));`? As this isn't working. – Martyn Ball Apr 03 '17 at 14:10
  • 1
    ah - you're not binding _within_ the class, so you'd have to supply `usedcars` as the parameter to `bind()`. Alternatively, do `addEventListener('click', () => usedcars.toggleActive())` – Alnitak Apr 03 '17 at 14:11
  • 1
    the correct form would be `usedcars.elm.addEventListener('click', usedcars.toggleActive.bind(usedcars))` – zzzzBov Apr 03 '17 at 14:11
  • (It's unusual for a control of this nature to rely on external code to bind its event listeners which is what caught me out first time around) – Alnitak Apr 03 '17 at 14:13

0 Answers0