从多个事件中调用一次函数

Call function once from multiple events

我一直在为一系列触摸屏设备开发网页,最常见的问题之一是如何处理触摸事件。

有没有一种很好的方法可以只调用一次函数,即使多个(大致)同时事件调用它也是如此?

例如

$("body").on("mousedown touchstart MSPointerDown", function () {
    alert("This message will appear multiple times on some devices.");    
})

我考虑过使用超时,这样该函数只能每 200 毫秒或类似的东西调用一次(超出我的头脑并且未经测试):

var allowed = true;
$("body").on("mousedown touchstart MSPointerDown", function () {
    if(allowed){
        allowed = false;
        alert("This message will hopefully only appear once!");
        setTimeout(function () { allowed = true }, 200);
    }
})

(对于这个问题,我不是在寻找插件建议,我知道有很多触摸事件插件)

是否有 proper/nicer 方法可以使用多个事件作为单个函数的可能触发器?我能否以某种方式为事件添加别名而不破坏它们的其他用途?

您可以使用 $.one(而不是 $.on)

此处:$.one documentation on jquery.com

如果您希望它随后被调用,那么您可以在超时时重新绑定处理程序,如下所示:

function handler(){
var called = false;
return function(ev){
    if(!called){
        called = true;
        $("ul#messages").append($("<li>").text("event"));
        setTimeout(bind, 1000); // rebind after a suitable pause
    }
}
}

function bind(){
    $("ul#messages").one("click", new handler())        
};

$(function(){
    bind();
});

https://jsfiddle.net/p3t6xo48/5/

这允许每个绑定的处理程序 运行 一次,并且仅一次,用于多个事件,然后在适当的暂停后反弹。

实际上,您希望只接受第一个事件 type 并忽略所有其他事件。这仍然会在未来 clicks/touches 发生。输入 closures.

$(document).ready(function() {
  function alertClosure() {
    var eventType = null;

    function doAlert(e) {
      if (!eventType) {
        eventType = e.type; // only the first eventType we get will be registered
      }

      if (e.type == eventType) {
        alert("This message will hopefully only appear once!: " + e.type);
      }
    }

    return doAlert;
  }

  $("body").on( "mousedown touchstart MSPointerDown", alertClosure() );
});

http://plnkr.co/edit/oz48d3