Skip to content

Instantly share code, notes, and snippets.

@brian-mann
Last active March 30, 2017 05:50
Show Gist options
  • Save brian-mann/5430655 to your computer and use it in GitHub Desktop.
Save brian-mann/5430655 to your computer and use it in GitHub Desktop.
keyboard shortcuts in marionette views with mousetrap lib
_delegate = Backbone.Marionette.View::delegateEvents
_close = Backbone.Marionette.View::close
_.extend Backbone.Marionette.View::,
delegateEvents: (events) ->
_delegate.call(@, events)
@bindShortCuts()
bindShortCuts: ->
for key, method of _.result(@, "shortCuts")
method = @[method] unless _.isFunction(method)
throw new Error("Method #{method} not found!") unless method
method = _.bind(method, @)
Mousetrap.bind(key, method)
close: ->
_close.call(@)
@afterClose()
afterClose: ->
@unbindShortCuts()
unbindShortCuts: ->
for key of _.result(@, "shortCuts")
Mousetrap.unbind(key)
## in your views somewhere
class Show.View extends Marionette.ItemView
shortCuts:
"command+ctrl+c" : -> @trigger "clone:last:point"
@d3chapma
Copy link

I have really appreciated this script. Thanks for posting it!

I have one problem though. The @unbindShortcuts method seems to be called after the @bindShortcuts method in the case of swapping two views in a region. This means that if I swap two views that implement the same shortcuts the end result is nothing being bound. It first binds the new shortcuts then unbinds the old ones effectively also unbinding the new shortcuts at the same time.

Any idea if there is a workaround for this?

@d3chapma
Copy link

I ended up doing this as a work around:

delegateEvents: (events) ->
      _delegate.call(@, events)
      bindShortCuts = _.bind(@bindShortCuts, this)
      _.delay bindShortCuts, 100

Don't perticularly like using a delay, but it works

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