Skip to content

Instantly share code, notes, and snippets.

@bayleedev
Last active February 27, 2017 23:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bayleedev/643dbc656da7c3c4ca050a7d8ed0a222 to your computer and use it in GitHub Desktop.
Save bayleedev/643dbc656da7c3c4ca050a7d8ed0a222 to your computer and use it in GitHub Desktop.
Mousetrap will only bind a key event to one function, this makes it so you can bind it to as many as you like.
class MousetrapProxy {
constructor () {
this.events = {}
}
emit (key) {
if (!this.events[key]) return
this.events[key].forEach((cb) => cb())
}
bind (keys, cb) {
const keysArray = typeof keys === 'string' ? [keys] : keys
keysArray.forEach((key) => {
if (!this.events[key]) {
this.events[key] = []
Mousetrap.bind(key, () => {
this.emit(key)
})
}
this.events[key].push(cb)
})
}
}
var ee = new MousetrapProxy();
ee.bind(['command+shift+k', 'up'], function (e) {
console.log('meow')
})
ee.bind('command+shift+k', function (e) {
console.log('ruff')
})
@bayleedev
Copy link
Author

bayleedev commented Feb 21, 2017

(function () {
  const events = {}
  const _old_mousetrap = Mousetrap.bind

  Mousetrap.bind = (keys, cb) => {
    const keysArray = typeof keys === 'string' ? [keys] : keys
    keysArray.forEach((key) => {
      if (!events[key]) {
         events[key] = []
         _old_mousetrap(key, () => {
           events[key].forEach((event) => {
             event()
           })
        })
      }
      events[key].push(cb)
    })
  }
})()

Mousetrap.bind(['command+shift+k', 'up'], function (e) {
    console.log('meow')
})

Mousetrap.bind('command+shift+k', function (e) {
    console.log('ruff')
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment