DEV Community

Discussion on: Creating and Consuming Custom Events

Collapse
 
parenttobias profile image
Toby Parent

Recently, there was a question in the Odin Project's Discord group about handling event listeners - in particular, "can we bind a key to a given element or action?" Key-binding is a useful utility, and can be done with vanilla js,but it could be handy to bind directly to a keystroke, rather than to all keyup events.

To see what I mean, we could do things like this:

document.addEventListener("ArrowLeft.up", (e)=>{
  if(e.detail.modifers.shift){
    counter -= 10;
  } else {
    counter -= 1;
  }
});
document.addEventListener("ArrowRight.up", (e)=>{
  if(e.detail.modifiers.shift){
    counter += 10;
  } else{
    counter += 1;
  }
});
Enter fullscreen mode Exit fullscreen mode

With that, for example, we could do a simple js game loop. We can listen for arrow keys or specific action keys, and check for modifiers on them, and respond appropriately.

And we're not having to duplicate the if(e.key==='ArrowLeft'') or if(e.key==='ArrowUp') checks each time. We bind to a custom event indicating which key is pressed: in effect, key binding.

Here's the code I put together in playing with this one.

const init = ()=>{
  document.addEventListener("keydown", (e)=>{
    document.dispatchEvent(new CustomEvent(`${e.key}.down`, {
      detail: {
        modifiers: {
          alt: e.altKey,
          shift: e.shiftKey,
          meta: e.metaKey,
          ctrl: e.ctrlKey
        }
      }
    }))
  });
  document.addEventListener("keyup", (e)=>{
    document.dispatchEvent(new CustomEvent(`${e.key}.up`, {
      detail: {
        modifiers: {
          alt: e.altKey,
          shift: e.shiftKey,
          meta: e.metaKey,
          ctrl: e.ctrlKey
        }
      }      
    }))
  })
}
Enter fullscreen mode Exit fullscreen mode

And to tinker with it: replit.com/@TobiasParent/CustomKey...