1
\$\begingroup\$

I have written the following Javascript class

function InScroll( container, options ) {
    "use strict";

    var isRunning = false;
    // utilities
    var noop = function() {};

    var inter = null;

    if(!container) {
        alert('container element not provided');
        return;
    }
    if(!options.interval) options.interval = 500;

    // save screen info
    var page = {
        contentHeight: $(container).getHeight(),
        pageHeight: document.viewport.getHeight(),
        scrollPosition : 0,
    }

    function scroll() {
        var pos = $(container).select("div.kurz").length;

        if(pos == 0) {
            this.kill();
            return;
        }

        // get scroll position y-axis.
        page.scrollPosition = document.viewport.getScrollOffsets()[1];

        if( !isRunning && (page.contentHeight - page.pageHeight - page.scrollPosition ) < 450) {        
            new Ajax.Request(options.url + "?pos=" + pos, {
                onCreate: onCreate,
                onSuccess: append,
                onFailure: error,
                onComplete: onComplete

            });
        }
    }
    function onCreate() {
        isRunning = true;
    }

    function onComplete() {
        isRunning = false;
        page.contentHeight= $(container).getHeight();

    }

    function append( response ) {
        var resp = response.responseText.strip();

        if(resp == "") kill();

        container.innerHTML += resp;
    }

    function error( response ) {
        var resp = response.responseText.strip();
        container.innerHTML += resp;
    }

    function start() {

        if(!container) {
            alert('container element not provided');
            return;
        }

        if(!options || !options.url) {
            alert('content loader script should be set as options.url');
            return;
        }

        (function(that) {
            inter = window.setInterval( function() { that.scroll()}, 50);
        })(this)
    }

    function kill() {
        clearInterval(inter);
        $(options.loader).hide();
    }

    return {
        start: start,
        kill : kill,
        scroll: scroll
    }
}

Here I wanted to expose only the start and kill functions but due to the use of windows.setInterval i had to expose also the scroll function.

Can someone please have a look at the code, and give some suggestion how may I optiomize it?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

It seems to me that you don't need the self invoking function and the anonymous function:

inter = window.setInterval( scroll, 50);

should do

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.