如何解绑mousemove事件监听器?现有代码失效求解决方案
The core problem here is that every time you call clearIdleInterval.bind(this), you’re creating a brand new function reference. When you try to unbind later using the same bind() call, jQuery can’t match it to the original listener you attached—they’re two distinct functions, even though they behave identically.
The Fix: Store the Bound Function
Instead of calling bind() directly inside the event attachment, create a variable to hold the pre-bound version of your function. Use this variable both when adding and removing the event listener, so jQuery can correctly identify the function to unbind.
Here’s the corrected code:
// Store the bound version of your function first var boundClearIdleInterval = clearIdleInterval.bind(this); var clearIdleInterval = function () { console.dir('unbind'); clearInterval(this.idleInterval); $(document).unbind('mousemove', boundClearIdleInterval); $(document).unbind('keypress', boundClearIdleInterval); }; // Attach events using the stored bound function $(document).bind('mousemove', boundClearIdleInterval); $(document).bind('keypress', boundClearIdleInterval);
Bonus: Use Modern jQuery Syntax
Note that .bind() and .unbind() are deprecated in jQuery 3.0 and later. For better compatibility, switch to .on() and .off()—the logic stays the same with the stored bound function:
var boundClearIdleInterval = clearIdleInterval.bind(this); var clearIdleInterval = function () { console.dir('unbind'); clearInterval(this.idleInterval); $(document).off('mousemove', boundClearIdleInterval); $(document).off('keypress', boundClearIdleInterval); }; $(document).on('mousemove', boundClearIdleInterval); $(document).on('keypress', boundClearIdleInterval);
By reusing the exact same function reference for both attachment and removal, jQuery can properly unbind your mousemove and keypress listeners when you call clearIdleInterval.
内容的提问来源于stack exchange,提问作者Chris Hansen

