从对象动态设置 Mousetrap.bind() 组合键

Dynamically set Mousetrap.bind() key combinations from an object

我正在从我们的后端取回数据,其中包含有关键盘快捷键的信息。这是我将收到的简化版本:

    { code: "r", message: "test R" },
    { code: "s", message: "test S" },
    { code: "c", message: "test C"}

'Code' 指定哪个键将激活键盘快捷键,消息是将粘贴到输入框中的内容。

我正在使用 Mousetrap 库,它允许我编写如下函数:

Mousetrap.bind('shift+^+r', function () {
    alert("test");
});

我的问题是:有没有办法根据带回来的数据在运行时编写这些函数?因此,对于 JSON 对象中的每个项目,都需要一个函数来处理快捷方式。

我试过这个:

    var html = document.getElementById("shortcuts").innerHTML;
    document.getElementById("shortcuts").innerHTML = html + "<script> Mousetrap.bind('shift+^+r', function () { alert('test) })); <\/script>"

我不知道这是否是个好习惯,因为我对 JS 还是很陌生,但这是我唯一能想到的。虽然它不起作用。

当然可以。听起来很容易。只需创建一个接受对象的单独函数,同时获取 codemessage 属性并在运行时调用 Mousetrap.bind(str, func)

function bindKey(input){
    const code = input.code;
    const message = input.message;

    const bindStr = "shift+^+" + code; //idk if you need shift here but modify as needed

    Mousetrap.bind(bindStr, function(){
          alert(message);
    });
}

通过

使用
bindKey({code: "r", message: "test R"});
bindKey({code: "c", message: "test C"});
bindKey({code: "d", message: "test D"});

如果你有一个对象数组,只需遍历它们并调用 bindKey()

myArray.forEach(bindKey);
// or
for (const i of myArray) bindKey(i);

无需编写脚本元素。只需编写函数并在运行时调用它。为什么你需要呈现脚本标签超出了我的范围。


下面测试

function bindKey(input){
   const code = input.code;
   const message = input.message;

   const bindStr = "shift+^+" + code; //idk if you need shift here but modify as needed
    
    Mousetrap.bind(bindStr, function(){
          console.log(message);
    });
}
    
bindKey({code: "r", message: "test R"});
bindKey({code: "c", message: "test C"});
bindKey({code: "d", message: "test D"});
<script src="https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js"></script>

您可以遍历所有对象,在将键与每个对象的 code 绑定后,您可以搜索数组并选择元素来显示消息。适度实施:

var data = [{code:"r",message:"test R"},{code:"s",message:"test S"},{code:"c",message:"test C"}];

//use forEach to go through each item in data
data.forEach(key => {
  //call MouseTrap bind on key.code, key is one of the element in data
  Mousetrap.bind('shift+^+' + key.code, (e) => {
    //e is the event variable from the keystroke
    
    //data.find will find the element which has the key value(e.key) from the event
    //converting into lowercase because data is in lowercase too
    var element = data.find(d => {
      //check if code of the element matches e.key
      if (d.code == e.key.toLowerCase()) return d;
    });
    //log element.message
    console.log(element.message);
  });
});
<script src="https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js"></script>


来自@Bergi, @AZ_的建议:

var data = [{code:"r",message:"test R"},{code:"s",message:"test S"},{code:"c",message:"test C"}];

data.forEach(({code, message}) => Mousetrap.bind(`shift+^+${code}`, () => console.log(message)));
<script src="https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js"></script>