开发者

Am I adding a bunch of unnecessary event handlers?

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);      
    开发者_运维百科    }
    }


Why not simply bind the scroll event once, and then when the size is below a threshold, update a variable to enable it?

AKA

$(window).resize(function() { });
$(window).scroll(function()
{
     if( /* Check to see if window is greater than some set size */ )
         return;

     // Do Logic
});


Consider this:

$( window ).bind( 'scroll', function () {

    if ( $( obj ).height() + topOfSideBar < $( window ).height() ) {
        fixIt();
    } else {
        dynamicallyAdjustIt();
    }

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜