简体   繁体   English

jQuery-从元素中删除所有事件侦听器

[英]JQuery - Remove all event listeners from an element

I am implementing swipe functionality to change pages in a website for use with mobile devices using the plugin found here ( http://www.netcu.de/jquery-touchwipe-iphone-ipad-library ). 我正在使用此处找到的插件实现滑动功能,以更改网站上的页面以与移动设备一起使用( http://www.netcu.de/jquery-touchwipe-iphone-ipad-library )。 I have also included the plugin code at the bottom of this question. 我还在此问题的底部添加了插件代码。

The swipe functionality itself is fine, but due to the fact that I am loading pages using AJAX, new event handlers are being added every time a new page is loaded, and so the event handlers are conflicting. 滑动功能本身很好,但是由于我使用AJAX加载页面的事实,每次加载新页面时都会添加新的事件处理程序,因此事件处理程序存在冲突。

I did initially think that the problem was because I am testing on android and the plugin is not fully tested, but the problem is the same for iOS devices as well. 最初我确实以为问题是因为我正在android上进行测试,而插件尚未经过全面测试,但问题也适用于iOS设备。

I have tried using stopImmediatePropagation(), but that means that only the first handler is used, not the last, meaning that the same page is loaded repeatedly instead of the next one. 我尝试使用stopImmediatePropagation(),但这意味着仅使用第一个处理程序,而不使用最后一个处理程序,这意味着将重复加载同一页而不是下一个。 I have also tried using off() and unbind(), but these do not remove the handlers. 我也尝试过使用off()和unbind(),但这些操作不会删除处理程序。

Seeing as the handlers are added using addEventListener in the plugin, I assume that the only way to remove them is to use removeEventListener. 看到处理程序是使用插件中的addEventListener添加的,我假设删除它们的唯一方法是使用removeEventListener。 However, I am having trouble referring to the names of the functions as they have been created in a plugin. 但是,我在引用函数名称时遇到了麻烦,因为它们是在插件中创建的。 If I can refer to the function names then I think that I can remove the listeners and then add the new one when the page is loaded. 如果我可以引用函数名称,那么我认为可以删除侦听器,然后在页面加载时添加新的侦听器。 If this isn't possible for any reason, is there a way of removing all listeners attached to an element other than off() or unbind()? 如果由于某种原因无法做到这一点,是否有办法删除附加到除off()或unbind()之外的元素上的所有侦听器?

Many thanks in advance. 提前谢谢了。 :) :)

Code for the touchwipe plugin: touchwipe插件的代码:

/**
 * jQuery Plugin to obtain touch gestures from iPhone, iPod Touch and iPad, should also work with Android mobile phones (not tested yet!)
 * Common usage: wipe images (left and right to show the previous or next image)
 * 
 * @author Andreas Waltl, netCU Internetagentur (http://www.netcu.de)
 * @version 1.1.1 (9th December 2010) - fix bug (older IE's had problems)
 * @version 1.1 (1st September 2010) - support wipe up and wipe down
 * @version 1.0 (15th July 2010)
 */
(function($) { 
   $.fn.touchwipe = function(settings) {
     var config = {
            min_move_x: 20,
            min_move_y: 20,
            wipeLeft: function() { },
            wipeRight: function() { },
            wipeUp: function() { },
            wipeDown: function() { },
            preventDefaultEvents: true
     };

     if (settings) $.extend(config, settings);

     this.each(function() {
         var startX;
         var startY;
         var isMoving = false;

         function cancelTouch() {
             this.removeEventListener('touchmove', onTouchMove);
             startX = null;
             isMoving = false;
         }  

         function onTouchMove(e) {
             if(config.preventDefaultEvents) {
                 e.preventDefault();
             }
             if(isMoving) {
                 var x = e.touches[0].pageX;
                 var y = e.touches[0].pageY;
                 var dx = startX - x;
                 var dy = startY - y;
                 if(Math.abs(dx) >= config.min_move_x) {
                    cancelTouch();
                    if(dx > 0) {
                        config.wipeLeft();
                    }
                    else {
                        config.wipeRight();
                    }
                 }
                 else if(Math.abs(dy) >= config.min_move_y) {
                        cancelTouch();
                        if(dy > 0) {
                            config.wipeDown();
                        }
                        else {
                            config.wipeUp();
                        }
                     }
             }
         }

         function onTouchStart(e)
         {
             if (e.touches.length == 1) {
                 startX = e.touches[0].pageX;
                 startY = e.touches[0].pageY;
                 isMoving = true;
                 this.addEventListener('touchmove', onTouchMove, false);
             }
         }       
         if ('ontouchstart' in document.documentElement) {
             this.addEventListener('touchstart', onTouchStart, false);
         }
     });

     return this;
   };

 })(jQuery);

Check this code: 检查此代码:

var test = $( "<div></div>" ); // example element
test . click ( function () {} );
test . mouseover ( function () {} );
$.each ( $._data ( test [ 0 ], "events" ), function ( name ) // first argument of function: "$._data ()" is: "Element" - not jQuery object
{
    //console . log ( name ); // output: "click" and "mouseover
    test . off ( name ); // function off() removes an event handler
} );
// alert ( typeof $._data ( test [ 0 ], "events" ) ); // return "undefined" - no events

More on: jQuery function off . 更多信息: jQuery函数关闭
Working fiddle: JSFiddle . 工作提琴: JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM