handleEvent: ['on']?

handleEvent: ['on']?
0

#1

What does [‘on’] mean in this context? I just can´t seem to get my head around it:

// interface
var EventListener = {
  handleEvent(e) {
    this['on' + e.type](e);
  }
};

// component
var Clicker = Object.create(EventListener, {
  clicks: {writable: true, value: 0},
  onclick: {value(e) {
    e.preventDefault();
    console.log(++this.clicks);
  }}
});

// object
var clicker = Object.create(Clicker);
document.body.addEventListener('click', clicker);

#2

I’m not really sure what is going on with that code but I think the ‘on’ is the “on part” of the ‘onclick’ property and e.type is the ‘click’ part

console.log(e.type);
// Returns click
console.log(this['on' + e.type]);
// Returns 
value(e) {
  e.preventDefault();
  console.log(++this.clicks);
}

#3

Thanks for the answer! I got it off this page: https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38

Your explanation makes sense!


#4

It’s an interesting way to do event handling, but I don’t feel super comfortable about it, this['on' + e.type](e) just doesn’t quite sit right with me. I would have to look into it a bit more.

Not convinced his argument for why the pattern is so uncommon is solid. I’m sure he’s really smart, but so are a lot of other devs, and you would think you would have seen this pattern a lot more in the wild (i haven’t). Maybe it’s just an uncommon pattern for no good reason…maybe not.

Pretty cool though, thanks for the link.


#5

Yeah, I agree. It does feel a bit hacky, for some reason. But it also does seem to simplify multiple events.