RobertWHurst / Keystrokes

Keystrokes as an easy to use library for binding functions to keys and key combos. It can be used with any TypeScript or JavaScript project, even in non-browser environments.
MIT License
156 stars 6 forks source link

bind onReleasedHandler in onPressedHandler doesn't work #53

Closed zjz958182284 closed 1 month ago

zjz958182284 commented 2 months ago

Describe the bug My device is Mac M1, When I bind the keyboard release event in the keyboard press event, releasing the keyboard does not trigger the keyboard release event.

To Reproduce run following code then press and release keyboard key 'control'

    const releaseFn = {
      onReleased: () => console.log('control released!'),
    };
    const pressFn = () => {
      console.log('control pressed!');
      bindKey('control', releaseFn);
      unbindKey('control', pressFn);
    };
    bindKey('control', pressFn);

see output only: 'control pressed!'

Expected behavior output: 'control pressed!' and 'control released!'

RobertWHurst commented 1 month ago

Calling bindKey and unbindKey inside the callback will not work.

In order to track press and release try:

bindKey('control', {
  onPressed: () => console.log('control pressed!'),
  onReleased: () => console.log('control released!'),
})

Trying to bind a release handler while the key is being pressed is not how the library is meant to be used. Instead bindings should be bound before the key is pressed and released.

Let me know if that resolves your issue.