Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@bayleedev 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