Add Keybinding to Button


#1

Is there a way to add a keybinding to a button without using keymaps/PACKAGE.cson?

I am after just using a keybinding to trigger the same function as pressing a button.


#2

hi @Arcath, not sure if this is what you are asking for , but there is already feature request. Basically it is planned to add easy way how to change keybinding by pressing buttons in settings view.


#3

Hello,

I don’t know much about your specific use case, but if it were me, I would associate a command to the function triggered by the button so that it can be bound to a keybinding. However I would still use the keymap file as the preferred place to define the keybinding.

Here’s a basic example:

# In your view, the one with the button
initialize: ->
  atom.commands.add 'atom-workspace', {
    'my-package:my-command' => @myCommand()
  }
  
  @myButton.on 'click', => @myCommand()

myCommand: ->
  # Do something

The atom.commands.add 'atom-workspace' call will register the passed-in commands to be triggered on the specified selector or element (in that case the workspace)

Then, you can put a keybinding in the keymap file:

'atom-workspace': 
  'cmd-shift-alt-f': 'my-package:my-command'

#4

@abe Thanks, I thought this might be the case I just wondered if I could add a keybinding to the button on the screen instead.


#5

The thing is that you don’t really want to attach a binding to a button, you generally want to attach a binding to an action, a command (whatever name you use), the button itself is like a (visual) binding to an action.

To go a little further, it’s possible to attach a binding to the button, but that will means the binding will only effective when the button get the focus. Using the same example as before, the command registration would then look like this:

atom.commands.add '.my-container .my-button' {
  'my-package:my-command' => @myCommand()
}

That way the command will only trigger if the button has the focus. Not really useful, ain’t it?

For a real word example, I recommend taking a look to the find-and-replace package, where you have both buttons and keybinding to toggle the options:

https://github.com/atom/find-and-replace/blob/bo-api-upgrade/lib/find-view.coffee#L124-L131

:warning: Note that this version is not the one in master, but the one based on the new command API.