简体   繁体   English

删除滚动事件未按预期进行

[英]Removing scroll event didn't work as expected

I have the following code structure: 我有以下代码结构:

function somefunc(m) {
   function anotherfunc() {
      ...
      if ( m > ... 
      ...
   }
   console.log($._data(window).events.scroll);
   // $(window).off("scroll");
   $(window).off("scroll", anotherfunc);
   $(window).on("scroll", anotherfunc);
}
checkfunc() {
   if (...) {
      somefunc("1");
   }
   else (...) {
      somefunc("2");
   }
}
$(window).resize(function() {
   checkfunc();
});

Please don't mind the "logic" of m and binding/unbinding scroll event, and what I'm trying to achieve by it, the problem(and the question) is why can't I unbind the scroll event. 请不要介意m和绑定/取消绑定滚动事件的“逻辑”,而我试图通过它来实现的问题(和问题)是为什么我不能取消滚动事件的绑定。

The thing is, when I use: 事情是,当我使用:

$(window).off("scroll", anotherfunc);
$(window).on("scroll", anotherfunc);

in the above example, I assume that each time on window resize it will unbind previous scroll event of anotherfunc and bind a new one, but instead(as it can be seen by console.log($._data(window).events.scroll); it multiply it each time... 在上面的示例中,我假设每次在窗口调整大小时,它将取消绑定anotherfunc先前滚动事件并绑定一个新的滚动事件,但是相反(如console.log($._data(window).events.scroll);可以看到的那样console.log($._data(window).events.scroll);每次都会相乘...

For testing purpose I tried to remove the $(window).off("scroll", anotherfunc); 为了测试目的,我试图删除$(window).off("scroll", anotherfunc); and put instead of it $(window).off("scroll"); 而不是放$(window).off("scroll"); , and surprisingly it did unbind all previous scroll events. ,而且令人惊讶的是,它确实取消了所有以前的滚动事件的绑定。

My question is what is the difference here, because there's no other scroll events in there, so why 我的问题是,这里有什么区别,因为那里没有其他滚动事件,所以为什么

$(window).off("scroll", anotherfunc);
$(window).on("scroll", anotherfunc);

doesn't work the same way? 不能以相同的方式工作?

I think the correct syntax would be : 我认为正确的语法是:

$(window)
   .off("scroll") // Remove all scroll events. No callback or other action needed.
   .on("scroll", anotherfunc)

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

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