【问题标题】:Should I remove event listeners in jQuery?我应该在 jQuery 中删除事件侦听器吗?
【发布时间】:2015-06-28 16:36:01
【问题描述】:

我的网站在 jQuery + AJAX 上运行,并且只有一个 javascript 文件,当用户打开任何页面时都会加载一次,所以我习惯于为所有元素添加事件侦听器,例如:$(document).on(...)。

有一段时间我注意到代码中有太多.on(...),我很害怕。每次用户单击链接/返回按钮时,我都会服用 9 颗药丸并强制它删除无用的听众。

function page_reload(){
   if(c.r == 'http://example.com/page1'){
      $(document).on('click', '#send', func.send);
      $(document).on({mouseenter: func.me, mouseleave: func.ml}, '#chan');
   }else{
      $(document).off('click', '#send');
      $(document).off('*', '#chan');
   }
}

那么有什么意义吗?也许很多听众做了一些我不知道的坏事?

【问题讨论】:

    标签: javascript jquery event-handling


    【解决方案1】:

    当您将侦听器附加到事件时,它确实会占用内存,并且它可能(如果完全未检查)会导致与内存相关的问题。根据我的经验,最好在您的对象中使用 cleanup 方法,当某个事件触发时,您可以使用您的 .off() 方法取消注册您的事件侦听器。

    这些类型的方法的特定逻辑将根据您的项目而有所不同,但形式如下:

    var MyApp = {
      cleanup: function cleanMyApp(event) {
        this.off('#myId1', myMethod1);
        this.off('#myId2', myMethod2);
      }
    }
    
    $('document').on('ready', function() {
      $(document).on('importantEvent', function(event) {
        event.preventDefault(); // if you need to
        MyApp.cleanup();
      });
      // or 
      $('#elem').on('something', MyApp.cleanup);
    });
    

    所以是的,一次注册的监听器过多可能会导致问题,但您可以使用浏览器的开发工具等监控内存使用情况。特别是您可能会用完堆栈(和堆?)内存并可能导致浏览器崩溃。

    还有一个很好的答案here 处理这类问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 2022-08-03
      • 1970-01-01
      • 2011-03-07
      • 1970-01-01
      相关资源
      最近更新 更多