commands

commands二级模块对象,用于处理和命令相关的逻辑。命令包含2部分:唯一ID和自定义的function,可以通过registerCommand或registerTextEditorCommand注册。

命令可以通过以下方式触发:

声明command

菜单:将命令通过menus扩展点关联到某个菜单。

  1. 通过commands扩展点声明一个command,然后关联到menus
  1. {
  2. "contributes":{
  3. "commands":[
  4. {
  5. "command":"extension.firstExtension",
  6. "title":"My First Extension"
  7. }
  8. ],
  9. "menus":{
  10. "editor/context":[
  11. {
  12. "command": "extension.firstExtension",
  13. "group": "z_commands",
  14. "when": "editorTextFocus"
  15. }
  16. ]
  17. }
  18. }
  19. }
  1. 在插件的激活回调(activate)中注册该command
  1. hx.commands.registerCommand('extension.firstExtension',()=>{
  2. hx.window.showInformationMessage("Hello My First Extension.");
  3. });

用户自定义快捷键

用户自定义快捷键:使用插件的用户可以通过得知命令的ID(一般在package.json中有声明),然后通过自定义快捷键配置一个快捷键。

  1. // Keybindings.json;
  2. [
  3. {
  4. "key":"ctrl+shift+0",
  5. "command":"extension.firstExtension"
  6. }
  7. ]

executeCommand

执行指定id的命令。除了插件扩展的命令外,还可以执行HBuilderX内置的命令,完整的内置命令列表可以通过HBuilderX的顶部菜单工具-自定义快捷键,然后在打开的配置文件左侧部分找到所有列出的command字段,如下图:

commands - 图1

参数说明
参数名称 参数类型 描述
command String 要执行的命令id
返回值
返回类型 描述
Promise Promise对象
示例
  1. //执行插件扩展的命令
  2. hx.commands.executeCommand('extension.firstExtension')
  3. //执行内置的命令(关闭所有打开的编辑器)
  4. hx.commands.executeCommand('workbench.action.closeAllEditors')

registerCommand

注册一个指定id的命令,并关联一个自定义的函数

参数说明
参数名称 参数类型 描述
commandId String 命令id
handler Function 命令触发时执行的函数
返回值
返回类型 描述
Disposable 命令的销毁器,可将该对象放置到插件的context.subscriptions数组内,插件卸载时,将会自动注销该命令
示例
  1. let disposable = hx.commands.registerCommand('extension.firstExtension',()=>{
  2. hx.window.showInformationMessage("Hello My First Extension.");
  3. });
  4. context.subscriptions.push(disposable);