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?
-
\$\begingroup\$ If you are using ES6 you can use either let or consts. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… \$\endgroup\$Sean– Sean2016年11月24日 01:04:25 +00:00Commented Nov 24, 2016 at 1:04
1 Answer 1
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"); } );