我有一个触发屏幕大小调整操作的函数:
if ( window.addEventListener ) {
// For all major browsers, except IE 8 and earlier
window.addEventListener('resize', debounce(function () {
if ( $videosContainer.attr('data-video-hosting') === 'youtube' ) {
resizeVideo(netVidX, netVidY, cryptoVidX, cryptoVidY, 'youtube');
}
}, 250));
} else if (window.attachEvent ) {
// For IE 8 and earlier versions
window.attachEvent('resize', debounce(function () {
if ( $videosContainer.attr('data-video-hosting') === 'youtube' ) {
resizeVideo(netVidX, netVidY, cryptoVidX, cryptoVidY, 'youtube');
}
}, 250));
}
防抖动机制定义如下:
// Smart debounce. Source - https://gist.github.com/vincentorback/9649034
// it works the exact same way as you'd expect, except it only fires once the keypress event is idle for XX ms
function debounce(fn, wait) {
var timeout;
return function () {
clearTimeout(timeout);
timeout = setTimeout(function () {
fn.apply(this, arguments)
}, (wait || 1));
}
}
由于此函数被反复调用,因此我想删除监听器/取消绑定,然后再添加(再次)。它在视频的滑块中,我需要重新设置调整大小的侦听器,因为某些本地范围设置和事实视频的尺寸不同,比如说长话长说……)
在jquery中,我可以按照以下方式进行操作:
$video.off('resize').on('resize', function(e) {
在javascript中,我可以使用removeEventListener
if (window.removeEventListener) {
window.removeEventListener('resize', functionToUnbind, false);
} else if (window.detachEvent) {
window.detachEvent('resize', functionToUnbind, false);
}
但是我的问题是,由于去抖动的位置,我无法使removeEventListener正常工作。
我尝试将所有“去抖动块”放入一个名为functionToUnbind的新函数中,以便能够使用如上所示的标准removelistener方法,但是它不起作用。
launchStuffForLatestSliderVideo();
function launchStuffForLatestSliderVideo() {
//remove first any lingering/remaining/existing resize listener on the videos
if (window.removeEventListener) {
window.removeEventListener('resize', functionToUnbind, false);
} else if (window.detachEvent) {
window.detachEvent('resize', functionToUnbind, false);
}
function functionToUnbind() {
debounce(function () {
if ( $videosContainer.attr('data-video-hosting') === 'youtube' ) {
resizeVideo(netVidX, netVidY, cryptoVidX, cryptoVidY, 'youtube');
}
}, 250)
}
//reset a new event listener for the latest video
if ( window.addEventListener ) {
// For all major browsers, except IE 8 and earlier
window.addEventListener('resize', functionToUnbind);
} else if (window.attachEvent ) {
// For IE 8 and earlier versions
window.attachEvent('resize', functionToUnbind);
}
}
每次重新设置监听器之前,应该如何删除它?我认为问题出在防弹跳上,但我不确定
问题在于,您尝试使用它的方式,每个resize事件都会对timeout
变量有不同的引用。
由于您始终将事件处理程序设置在window
仅具有一个实例的全局对象上,因此您可能会更改timeout
为处于全局范围内,因此它也只有一个实例。
为此,您应该将debounce
函数更改为如下所示:
var globalResizeTimeout;
function debounce(fn, wait) {
clearTimeout(globalResizeTimeout);
globalResizeTimeout = setTimeout(function () {
fn.apply(this, arguments)
}, (wait || 1));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句