0

我遇到了一个防止双重事件的问题

所以首先我有一段代码触发

jQuery(window).trigger('swipeForward');

所以这会监听这个触发器

jQuery(window).on('swipeForward', swipeHandlerNext );

滑动处理程序的想法是让用户不能滑动两次并创建一个双事件

然后这将执行 swipeHandlerNext 函数

function swipeHandlerNext(event) {

    // If event isn't already marked as handled, handle it
    if(event.handled !== true) {

        // Kill event handler, preventing any more clicks
        jQuery(".pageSize").off("swipeForward");

        // Do your stuff here
        pageSize = jQuery(".mainHeader").width();
        slide("forward", pageSize);

        console.log(" swipe complete page forward via swipe");

        // Mark event as handled
        event.handled = true;
    } 

    return false;
}

这显然执行了滑动功能。这是具有 .animate 命令的那个

function slide(data, pageSize) {


    if (!pageSize) {
    pageSize = jQuery(".mainHeader").width();
    }

    var promise  = calcLeft(data, pageSize);


    jQuery.when(promise).then(function(result) {

        console.log(result);

        jQuery('#pageHolder').delay(500).animate({
            left: result

          }, 400, function() {
            console.log("animation started");
            calcNav(pageSize);
            calcPage(pageSize);
            jQuery(".pageSize").on("swipeForward", swipeHandlerNext);
            console.log("animation complete");

        });


    });

}

然而,这并不能阻止双滑。

谢谢你的帮助

4

1 回答 1

2

为什么Off()在您的示例中不起作用

jQuery 的off()方法期望选择器为match the one originally passed to .on() when attaching event handlers.

在您的初始事件绑定中,您将事件附加到window带有jQuery(window).on(...). 但是在处理程序函数中,您要删除事件,然后使用and将事件重新附加到.pageSize元素。jQuery('.pageSize').off(...)jQuery('.pageSize').on(...)

换句话说,您实际上并没有删除绑定到window元素的事件处理程序,因此用户可以继续滑动。

为什么event.handled在您的示例中不起作用

每次滑动事件发生时,都会创建一个单独 event的对象并将其传递给处理程序。因此,该event对象不是一个全局变量,您可以在后续滑动中对其进行修改和检查其状态。

按照您的示例可能的解决方案

  1. 匹配传递给on()andoff()方法的选择器。
  2. 设置和取消设置全局变量以指示正在进行滑动。
于 2013-02-22T00:39:57.717 回答