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?

asked Nov 23, 2016 at 23:28
\$\endgroup\$
1

1 Answer 1

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"); } );
answered Nov 23, 2016 at 23:54
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.