0

I'm trying to use ES6 classes to setup UI components, currently playing around with the pattern, it's a little new to me.

I want to bind a click event onto the DOM element so I can call an associated method.

The below is what I've got so far, but the method isn't being called correctly, I'm getting a TypeError. Also, I can imagine my index.js file getting really bloated and confusing in a large project, is there a better approach? Any other advice would be much appreciated?

header.js

export default class Header {
   constructor(element) {
      element.addEventListener('click', () => this._clicked());
   }

   _clicked() {
      console.log("clicked the Header Component");
      console.log(this);
      this.classList.add('hidden');
   }
}

index.js

import Header from '/javascripts/Header';

$(function(){
  var HeaderElement = document.getElementsByClassName('city-picker');
  new Header(HeaderElement);
});    
jsldnppl
  • 915
  • 1
  • 9
  • 28
  • 1
    Did you do any basic debugging to see what `HeaderElement` actually is and what `element` in your constructor actually is? – jfriend00 Jan 03 '18 at 16:50
  • @jfriend00 is correct. Check out the duplicate question, you're targeting ALL elements vs the specific element with that selector. – Drew Dahlman Jan 03 '18 at 16:51
  • I presumed because there was only one instance of the class on the page, it would be automatically select. Added var input = element[0]; and it worked correctly. – jsldnppl Jan 03 '18 at 17:16

0 Answers0