javascript - 在 jQuery Mobile 中使用allowSamePageTransition 时如何正确取消绑定(bind)事件?

标签 javascript jquery jquery-mobile binding jquery-events

我正在使用 jQuery Mobile 选项allowSamePageTransition,这使我能够从

A页 > A页 > A页 ...

我需要它来浏览项目目录。我的问题是,这些项目需要某种形式的交互,我曾经将交互绑定(bind)附加到 document,因为它是在生成受影响的元素之前设置的。

但是,一遍又一遍地重新加载同一页面将在每次重新加载时重新绑定(bind)我的事件处理程序。

我的第一个想法是在页面隐藏时使用.off,但是重新加载页面#foo,将触发pagehide on显示相同的页面,因此所有绑定(bind)都设置为

$(document).on("pagebeforeshow.foo_events", "#foo", function(e) {
  // bind when shown
});

将因之前的#foo被隐藏而再次解除绑定(bind)

$(document).on("pagehide", "#foo", function (e) {
  $(this).off(".foo_events");
  // removes bindings on #foo being hidden AND shown
});

我想出的唯一解决方案是在文档上添加类,但我不喜欢这样做:

priv.setBindings = function (param) {
    var doc = $(document);

  doc
    .filter(function() { return $(this).is(".e_gallery") !== true; })
    .on("pagebeforeshow.gallery", param.pageId, function (e) {
      doc.addClass(".e_gallery");
      // run stuff
    });
};

但我不喜欢将类附加到 dom。

问题:
有没有办法防止在一遍又一遍地访问同一页面而不切换类的情况下在 $(document) 上设置多个事件绑定(bind)?

最佳答案

解决方案1

最好的解决方案是使用pageinit来绑定(bind)事件。如果您查看官方文档,您会发现 pageinit 只会触发一次,就像文档就绪一样,因此事件无法再次绑定(bind)。这是最好的解决方案,因为您没有像使用 off 方法删除事件时那样的处理开销。

工作 jsFiddle 示例:http://jsfiddle.net/Gajotres/AAFH8/

当然,如果使用多个 HTML 解决方案,这将会失败。

解决方案2

在绑定(bind)事件之前将其删除:

$(document).on('pagebeforeshow', '#index', function(){       
    $(document).off('click', '#test-button').on('click', '#test-button',function(e) {
        alert('Button click');
    }); 
});

工作 jsFiddle 示例:http://jsfiddle.net/Gajotres/K8YmG/

解决方案3

使用 jQuery 过滤器选择器,如下所示:

$('#carousel div:Event(!click)').each(function(){
    //If click is not bind to #carousel div do something
});

因为事件过滤器不是官方 jQuery 框架的一部分,所以可以在这里找到:http://www.codenothing.com/archives/2009/event-filter/

这可能是最好的解决方案,因为事件只会绑定(bind)一次。

解决方案4

可能是其中最简单的一个。

$(document).on('pagebeforeshow', '#index', function(){       
    $(document).on('click', '#test-button',function(e) {
        if(e.handled !== true) // This will prevent event triggering more then once
        {
            alert('Clicked');
            e.handled = true;
        }
    }); 
});

工作 jsFiddle 示例:http://jsfiddle.net/Gajotres/Yerv9/

这是一个与解决方案 3 180% 不同的解决方案,在这种情况下,事件将被绑定(bind)多次,但只允许执行一次。

更多信息

如果您想了解有关此问题的更多信息,请查看此 article ,包括工作示例。

关于javascript - 在 jQuery Mobile 中使用allowSamePageTransition 时如何正确取消绑定(bind)事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17927370/

相关文章:

php - 在模态中将 Jquery 变量传递给 php

android - 网络应用 : Hide a div except android browsers

javascript - 禁用页面上具有特定值的所有选择选项 - Javascript

javascript - RXJS 对另一个可观察值进行过滤

ajax - 登录适用于 iPhone,但不适用于 Android

jQuery Mobile + FullCalendar - 需要刷新页面才能看到

javascript - 更新后在 Jquerymobile 中刷新 Gridview

javascript - 多页面站点中 jQueryMobile/jQuery 的问题

javascript - FullCalendar 在周时间轴 View 中隐藏时间

javascript - 在 jquery 中显示数组中的元素