jaywcjlove / hotkeys-js

➷ A robust Javascript library for capturing keyboard input. It has no dependencies.
https://jaywcjlove.github.io/hotkeys-js
MIT License
6.67k stars 410 forks source link

同一键,绑定不同function,如何只触发一次? #19

Closed chenjf2k closed 6 years ago

chenjf2k commented 6 years ago

比如,我在公共js定义了esc function。 如果有个别页面已定义了esc,并且触发时返回false,则不再触发公共的esc function。

hotkeys('esc', function(event,handler){ $("<div>esc-fun1</div>").appendTo(document.body); return false; }); hotkeys('esc', function(event,handler){ $("<div>esc-fun2</div>").appendTo(document.body); return false; });

目前两个都会触发,我只想做得第一个返回false时,不再触发第二个,可以做到吗?

jaywcjlove commented 6 years ago

快捷键相同干不通的事儿

// 一个快捷键,有可能干的活儿不一样哦
hotkeys('ctrl+o, ctrl+alt+enter', 'scope1', function(){
  console.log('你好看');
});

hotkeys('ctrl+o, enter', 'scope2', function(){ 
  console.log('你好丑陋啊!');
});

// 你摁 “ctrl+o”组合键
// 当scope等于 scope1 ,执行 回调事件打印出 “你好看”,
// 当scope等于 scope2 ,执行 回调事件打印出 “你好丑陋啊!”,

// 通过setScope设定范围scope
hotkeys.setScope('scope1'); // 默认所有事儿都干哦
chenjf2k commented 6 years ago

谢谢,只是好像写法不够友好。 我要的效果,比如同key绑了2个(A、B),正常情况下两个function都会触发 (按绑定先后顺序),我希望先触发的function返回false时,后一个function不要触发了。

jaywcjlove commented 6 years ago

@chenjf2k

没有明白你的意思?

你是绑定了两个键? 你可以通过下面方式判断

hotkeys('a,b', function(event,handler){
  switch(handler.key){
    case "a":alert('你按下了r!');break;
    case "b":alert('你按下了f!');break;
  }
});
chenjf2k commented 6 years ago
    hotkeys('esc', function () {
        alert('esc1');
        if (true) return false;
    });

    hotkeys('esc', function () {
        alert('esc2');
    });

  我希望alert('esc2')的function不要执行,当前一个function 返回false时
jaywcjlove commented 6 years ago

@chenjf2k 这个是你的业务代码有问题。

hotkeys('esc', function () {
  alert('esc1');
  if (true) return;
  // 先判断你的条件,如果条件为 true 下面不执行,直接返回,条件为 false 接着走下面的。
  alert('放在这里就不触发了啊!');
});

hotkeys('esc', function () {
    alert('esc2');
});
chenjf2k commented 6 years ago

谢谢您不厌其烦的回复。 那样的话,代码只能放在一起,,,没法抽象通用的放在公共js 文件下。

jaywcjlove commented 6 years ago

@chenjf2k 一样可以抽象呢