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

时间:2019-07-18 10:33:57

标签: javascript mousetrap

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

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

“代码”指定将激活键盘快捷键的键,并且消息将粘贴在输入框中。

我正在使用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还是很陌生,但这是我唯一能想到的。它不起作用。

2 个答案:

答案 0 :(得分:3)

好的。听起来很容易。只需创建一个接受对象的单独函数,同时获取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>

答案 1 :(得分:2)

您可以遍历所有对象,将键与每个对象中的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>