Hacker News new | ask | show | jobs
by ender7 4916 days ago
Sadly, one last, unfortunate inconsistency:

All event handlers have the value of 'this' bound to the object that emitted the event:

  var div = document.createElement('div');
  div.addEventListener('click', function(e) {
    console.log(this); // prints <div></div>
  });
2 comments

That's not a JS inconsistency, that's just the browser calling yourhandler.call(yourobject, eventobject).

The underlying statement is that "event handler" is not a concept in JS, it's just a way of calling functions that some implementations use for some things (browsers for actions, node for I/O, etc...).

In fact, this didn't use to be true of old IE versions if I remember correctly, so it's not a matter of the language, but of what the browser does with your function during event firings.

You can get the current emitting object via e.currentTarget. Modifying 'this', while cute, just makes yet another thing that must be explained to people when you start talking about 'this'.
Unfortunate? Would you prefer to bind that yourself?
Would you prefer to bind that ['this'] yourself?

Certainly. Why should some state be teleported in magically while other state (the argument 'e' in the above example) has to ride the bus? Does it belong to a different class of Being? I don't think so. This forces me to spend precious brain cells remembering which things go in which buckets and what the rules are for accessing the buckets - i.e. busywork - rather than the problem at hand.

The easiest thing is to explicitly bind to just that state you need and ignore everything else. That's more or less what the argument "e" offers: it's a bag of all the goodies you might need while handling your event. Clearly, therefore, the DOM element emitting the event should be available through that same mechanism – and as you generally can get everything you need in that department through things like e.target, I find it simplest to remain blissfully ignorant of 'this'.

Agreed. Too bad we're stuck with Javascript.

EDIT: I meant that as a pronoun.