Comment

Comment by carussell

The unfortunate thing about the lengths people go to in order to try to "fix" `this` in event handlers is that it wouldn't be a problem if people just implemented the event listener interface correctly.

PSA Don't do this:

  proto.foo = function() {
    /* ... */
    var self = this;
    element.addEventListener("click", (function(event) {
      self.iHaveAnUnhealthyObsessionWithLambdas(event.target);
    }));
  }

  proto.iHaveAnUnhealthyObsessionWithLamdas = function(clicked) {
    /* do something with clicked element `clicked` */
  }
Do this instead:

  proto.foo = function() {
    /* ... */
    element.addEventListener("click", this);
  }

  proto.handleEvent = function(event) {
    /* do something with clicked element `event.target` */
  }
parent carussell 9 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton