我有一个触发屏幕调整大小动作的功能:
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));
}
}
由于重复调用此函数,我想在添加之前删除侦听器/解除绑定(再次)。这是一个视频滑块,我需要重新设置调整大小的侦听器,因为一些本地范围和事实视频没有相同的尺寸eahc时间...长篇故事...)
在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);
}
但我的问题是,由于debounce的位置,我无法使removeEventListener工作。
我尝试将所有“debounce block”放在一个名为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);
}
}
每次重新设置之前,我应该如何删除侦听器?我认为这个问题来自去抖,但我不确定
答案 0 :(得分:1)
问题在于您尝试使用它的方式,每个调整大小事件都会对import requests, bs4
site = 'http://www.goal.com/en-ie/news/ozil-agent-eviscerates-jealous-keown-over-stupid-comments/1javhtwzz72q113dnonn24mnr1'
p = requests.get(site).text
soupy = bs4.BeautifulSoup(p,"html.parser")
elems = soupy.select('img[src]')
for u in elems :
print (u)
变量有不同的引用。
由于您始终在具有一个实例的全局timeout
对象上设置事件处理程序,因此您可以将window
更改为全局范围,以便它也具有单个实例
为此,您应该将timeout
功能更改为:
debounce