我是否添加了一堆不必要的事件处理程序?
我怀疑我在这里使用的事件处理程序可能是错误的。有人可以指出我正确/更好的方法吗?
基本上我正在监视 window.resize 事件。如果窗口小于屏幕上的元素,我将绑定到滚动事件。我的问题是调整大小事件不断抛出。我认为这意味着我不断重新绑定到滚动事件。这看起来很糟糕。有没有想过更好的方法来做到这一点?
我可以使用一个变量来跟踪它是否已经绑定......但这对我来说似乎很笨重。
//when window is resized check whether the sidebar still fits on screen
$(window).resize(checkIt);
function checkIt() {
botOfSidebar = $(obj).height() + topOfSidebar;
if (botOfSidebar < $(window).height()) {
//discard event handler
$(window).unbind("scroll", dynamicallyAdjustIt);
fixIt(); //fix it in place
}
else {
console.log("dynamically adjust it");
$(window).scroll(dynamicallyAdjustIt);
}
}
I suspect that I may be using event handlers wrong here. Can someone please point me to a correct/better way of doing this?
Basically I am monitoring the window.resize event. If the window is smaller than an on screen element I bind to the scroll event. My problem is that the resize event gets thrown continuously. I think this means that I am continuously rebinding to the scroll event. That seems bad. Thoughts on a better way to do this?
I could use a variable to keep track of whether or not it is already bound... but that seems clunky to me.
//when window is resized check whether the sidebar still fits on screen
$(window).resize(checkIt);
function checkIt() {
botOfSidebar = $(obj).height() + topOfSidebar;
if (botOfSidebar < $(window).height()) {
//discard event handler
$(window).unbind("scroll", dynamicallyAdjustIt);
fixIt(); //fix it in place
}
else {
console.log("dynamically adjust it");
$(window).scroll(dynamicallyAdjustIt);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不简单地绑定滚动事件一次,然后当大小低于阈值时,更新变量以启用它?
又名
Why not simply bind the scroll event once, and then when the size is below a threshold, update a variable to enable it?
AKA
考虑一下:
Consider this: