1

Consider this code:

function Elements() {
    this.mainSection = document.querySelector('.main-section');
    this.searchBtn = document.getElementById('search');
    this.searchBar = document.querySelector('.search-bar');
    ...
  }

  var initiate = new Elements();

  initiate.toggleBar = function() {
    console.log(this.mainSection);
  }

  initiate.addClick = function() {
    this.searchBtn.addEventListener('click', this.toggleBar );
  }

  initiate.addClick();

On click event it returns undefined, with parenthesis it runs function automatically.

Why eventlistener behave this way?

P.S. I'm just learning Javascript, and trying to write flexible code. Is this a good practice what I am doing, or am I over complicating things?

nikitahl
  • 406
  • 2
  • 7
  • 16

1 Answers1

2

You can change

this.searchBtn.addEventListener('click', this.toggleBar );

to

this.searchBtn.addEventListener('click', this.toggleBar.bind(this));

for this code to work :)

The problem is that this context is lost for function this.toggleBar when you assign it to addEventListener. Please refer to https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_value_of_this_within_the_handler for further details.

MartyIX
  • 27,828
  • 29
  • 136
  • 207
  • 2
    Thanks. This solution works for my case. I was just reading explanation of '.bind()' on https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind#Examples – nikitahl Jan 16 '16 at 21:45