Skip to content

添加子命令

可以通过实现 ISubListCommand 和 IContainSubCommands 实现给命令添加子命令

csharp
using GrapeCity.Forguncy.Commands;
using System.Collections.Generic;
using System.ComponentModel;

namespace MyPlugin
{
    public class MyPluginCommand : Command, ISubListCommand, IContainSubCommands
    {
        [Browsable(false)]
        public List<Command> CommandList { get; set; } = new List<Command>();

        public IEnumerable<List<Command>> EnumSubCommands()
        {
            yield return CommandList;
        }
    }
}

代码说明

  1. 给 CommandList属性标注 [Browsable(false)] 避免CommandList属性出现在主命令的属性中

效果

1670600418504-876e8fc1-9720-4319-ae35-e34e384b632b.png

JavaScript 中需要添加对于的逻辑来执行子命令

javascript
class MyPluginCommand extends Forguncy.Plugin.CommandBase{
    execute() {
        this.CommandExecutor.excuteCommand(this.CommandParam.CommandList, {
            runTimePageName: this.CommandExecutingInfo.runTimePageName,
            commandID: "myCommand",
        });
    }
}

Forguncy.Plugin.CommandFactory.registerCommand("MyPlugin.MyPluginCommand, MyPlugin", MyPluginCommand);

WARNING

命令执行防抖:
为了避免相同的命令在短时间内多次执行,相同“commandID”的命令在短时间内(1秒内),只会被执行一次。如果希望命令在短时间内执行多次,可以把commandID设置为唯一值,例如
commandID: new Date().valueOf().toString()

给子命令添加初始参数

如果调用子命令时需要给子命令传递初始参数,需要如下修改Js代码

javascript
class MyPluginCommand extends Forguncy.Plugin.CommandBase{
    execute() {
        this.CommandExecutor.excuteCommand(this.CommandParam.CommandList, {
            runTimePageName: this.CommandExecutingInfo.runTimePageName,
            commandID: "myCommand",
            // 子命令初始参数
            initParams:{
                "aaa": 1,
                "bbb": 2
            },
            locationString: "我的命令" // 控制台日志中显示字符串
        });
    }
}

Forguncy.Plugin.CommandFactory.registerCommand("MyPlugin.MyPluginCommand, MyPlugin", MyPluginCommand);

通过执行日志,我们可以看到,在执行子命令之前会初始化上下文参数

1672738741729-60238e25-4d41-4793-a604-7a2a00d946aa.png

此时,后续命令可以使用变量 “aaa”和“bbb”了,但是,在设计器里没有办法选择相应的变量,为了让设计器中可以选择“aaa”和“bbb”变量,cs 文件需要做如下修改

csharp
using GrapeCity.Forguncy.Commands;
using System.Collections.Generic;
using System.ComponentModel;

namespace MyPlugin
{
    public class MyPluginCommand : Command, ISubListCommand, IContainSubCommands
    {
        [ResultToProperty]
        [Browsable(false)]
        public string SubCommandParam { get; set; } = "aaa";

        [ResultToProperty]
        [Browsable(false)]
        public string SubCommandParam2 { get; set; } = "bbb";

        [Browsable(false)]
        public List<Command> CommandList { get; set; } = new List<Command>();

        public IEnumerable<List<Command>> EnumSubCommands()
        {
            yield return CommandList;
        }
    }
}

设计器效果
1672739691213-ff46118a-e7e0-48cf-8a9b-5946b88bc849.png

WARNING

注意,这个设计器支持初始变量的功能并不完美,“aaa”和“bbb”这两个上下文变量,不光子命令会有提示,主命令的后续命令也会提示,这是一个限制。目前没有好的方案解决

更新: 2023-01-09 12:25:08
原文: https://www.yuque.com/robert-bh51n/ea8l6c/gxk00vanz5cuxg9h