简体   繁体   中英

How do I retrieve document data, using the module pattern?

I'm writing javascript in what I believe is the module pattern (I'm still quite new to programming, so forgive me if I use incorrect terminology).

The script below is intended to measure three things when the document loads:

  1. The distance the page has scrolled.
  2. The y-offset of #eventSideBar , relative to the document top,
  3. The overall height of the document.

(function (exocet, $, undefined) {

    var scrollDistance = function() {
        return $('body').scrollTop()
    }
    var sideBarOffset = function() {
        return $('#eventSideBar').offset().top;
    }
    var allHeight = function() {
        return $('body').height();
    }

    exocet.init = function() {
        console.log('Scroll distance: ' + scrollDistance() +
                    ' Sidebar offset: ' + sideBarOffset() +
                    ' Total height: ' + allHeight()
        );
    };

}(window.exocet = window.exocet || {}, jQuery));

$(document).ready(function() {
    exocet.init();
});

When logging these to the console, the only value that's consistently returned correctly (tested in Chrome) is sideBarOffset . Whereas scrollDistance always returns 0 and allHeight varies +/- about 1000px.

If I change exocet.init to the following:

exocet.init = function() {
    console.log('Scroll distance: ' + scrollDistance() +
                ' Sidebar offset: ' + sideBarOffset() +
                ' Total height: ' + allHeight()
    );
    $(document).scroll(function(){
        console.log('Scroll is now: ' + scrollDistance());
    });
};

I then always get the correct scroll position value. This gets the right result, but seems a bit hackish.

Is there a "proper" way to get the data I'm after without chaining document methods, as seems to be happening in my approach?

Sounds like what you need is:

$(document).scroll(function() { exocet.init(); });

Put that inside your ready callback. The results have to be logged when the user scrolls. Having to press refresh doesn't make much sense.

@beautifulcoder's example will work everytime the document scrolls. If you just want the scroll position on page load (ie, if a scroll position was saved previously on the page), then you can put your exocet.init() function in a load event handler with a short timeout to capture that initial scroll position:

    $(window).on('load', function() {
        setTimeout(function() {
            exocet.init();
        }, 200);
    });

If you want both, then use the scroll event handler as well.

Modified JSBin example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM