Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How does 'bind()' work on an event listener?

<button class="btn">Hello</button>
<button class="btn">Hola</button>
<button class="btn">Cześć</button>
function Greet(el) {
  this.el = el;
  this.sayHi = function() {
    alert(this.el.textContent);
  }
  this.el.addEventListener('click', function() {
     this.sayHi();
  }.bind(this));
}

var btns = document.querySelectorAll(".btn");

var buttonsArray = [];

btns.forEach(function(item) {
  buttonsArray.push(
    new Greet(item)
  ); 
});
this.el.addEventListener('click', function() {
     this.sayHi();
  }.bind(this));

When I remove "bind(this)" - I get an error. I'm just not 100% sure what is happening. Why am I getting that error?

this.el.addEventListener('click', function() {
     this.sayHi();
  });

Error:

Uncaught TypeError: this.sayHi is not a function
    at HTMLButtonElement.<anonymous> 

https://codepen.io/Woodenchops/pen/WBxxqY?editors=1010

1 Answer

Steven Parker
Steven Parker
243,173 Points

Normally, in an event handler the keyword "this" refers to the event object. But "sayHi" is a method of a "Greet" object and won't be found on an event object. What the "bind" does is cause the handler to run in the context of the "this" in effect when the listener is created instead of the one created when the event happens. And in this case, it is a "Greet" object.

For more details, see this MDN page on bind.