2
\$\begingroup\$

In my application I wrote a pagination code that retrieves data from the server as the user scrolls down. In this case, I need to mantain the current page, whether a request is being processed, and whether the server has more data to serve. I didn't want to use globals, but still needed to mantain these 3 variables state.

Here's my code:

fetchNextNotificationPage = (function() {

    var currentPage = 0;
    var maxPageHit = false;
    var fetching = false;

    return function () {

        // Prevent firing concurrent or pointless requests.
        if (fetching || maxPageHit) return;

        fetching = true;

       $.getJSON("GetPageUrl", { page: currentPage + 1 }, function (data) {

           if (!data.error) {

               // Finished fetching, so now it is safe
               // to say we are at previous page + 1.
               currentPage += 1;

               updateData(data.page);

               if (data.lastPage) {
                   maxPageHit = true;
               }
           }
           else {

               console.log(data.error);
           }

       }).always(function() {.

           fetching = false;
       });
   };
}());

Is there a better way to solve this other than using closure?

\$\endgroup\$
1
\$\begingroup\$

I think you have the right approaches, however, you can generalize your implementations, for example, on the second approach:

function installHandler ( that, eventName, userOneTime, userRegular ) {
    that.on(eventName, function ( event ) {
        that.off(eventName).on(eventName, userRegular);
        userOneTime ( event );
        userRegular ( event );
    });
}

installHandler ( $(this), "click", 
    function () { alert ("special click"); }, 
    function () { alert ("regular click"); } );
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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