如何在javascript中延迟先前绑定的事件?

时间:2018-11-03 07:14:18

标签: javascript

我有一个按钮,它在单击时执行特定的操作,该按钮来自框架的默认操作。我想延迟该功能(我不知道该按钮的绑定位置,我无法对其进行修改)

为简单起见,我将在此处提供具有两种不同功能的示例:

// lets say, this is the function which is bound from the framework, and I can't change:
$('button').on('click', function() {
  console.log('default click action');
});


// and I want to delay the action of the previous bound function from a new function without modifying the previous one, something like this:

$('button').on('click', function() {
  console.log('delayed both events for 1s'); // delay both of them for 1s.
});
button {
  border: 1px solid #cecece;
  padding: 5px 15px;
  font-size: 14px;
  border-radius: 4px;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type='button'> Try </button>

注意:不必更改函数的执行顺序,可以先执行第一个函数,没有问题。但是我需要能够从第二个功能中延迟第一个功能的执行。

1 个答案:

答案 0 :(得分:3)

我的想法是下一个:

如果您有修改元素结构的选项-您可以尝试用某些元素(例如button)包装span,并为click事件注册一个侦听器它在捕获阶段(请详细了解addEventListeneruseCapture参数。

当您在此类包装器上捕获到click事件时(该事件将在框架的处理程序处理之前)-您可以使用{在1秒钟之后停止该事件传播并触发新的自定义click事件{1}}。

setTimeout
// lets say, this is the function which is bound from the framework, and I can't change:
$('button').on('click', function() {
  console.log('default click action');
});

// and I want to delay the action of the previous bound function from a new function without modifying the previous one, something like this:


document.querySelector('.button-wrapper').addEventListener('click', function(event) {
  if (!event.detail || !event.detail.delayed) {
    event.stopPropagation();
    setTimeout(function(button) {
      button.dispatchEvent(new CustomEvent('click', {detail: {delayed: true}}));
      console.log('delayed both events for 1s');
    }, 1000, this.children[0]);
  }
}, true);
button {
  border: 1px solid #cecece;
  padding: 5px 15px;
  font-size: 14px;
  border-radius: 4px;
  font-weight: bold;
}