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);