Last active
March 30, 2017 05:50
-
-
Save brian-mann/5430655 to your computer and use it in GitHub Desktop.
keyboard shortcuts in marionette views with mousetrap lib
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_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" |
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
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?