DEV Community

Discussion on: The Fantastically Magical handleEvent Function

Collapse
 
thepeoplesbourgeois profile image
Josh • Edited

This post is great! If your event cases grow even farther than click and input, you can also implement dynamic dispatch to keep the complexity of handleEvent down:

const handler = {
  handleEvent(event) {
    return this[`${event.type}Event`] && // ensure that you don't throw if the function doesn't exist. 
                                  // Unless you prefer to surface those events, but you could also convert this to a ternary or `if-else` to log when a type you weren't expecting is sent through.
      this[`${event.type}Event`](event);
  }

  clickEvent(event) { /* ... */ }

  inputEvent(event) { /* ... */ }

  submitEvent(event) { /* ... */ }

  dragEvent(event) { /* yaaas! */ }

  techTalkEvent(event) { /* oooh, **takes notes**... */ }

}
Enter fullscreen mode Exit fullscreen mode

Oh yeah, and you can even assign different responsibilities to multiple handlers, then programmatically split up the behaviors of your UI, without ever having to worry about the memory or performance impacts of this.bind. AND!! The VM is smart enough not to assign the same handler to the same event more than once! handleEvent is LITERALLY the best.