I have this script which is for a news feed. A button click will grab more data from the server if there is any and then add it to the box. It doesn't allow any more than 10 pages of results currently and how to properly store that page counter is what this question is about. loadMoreFeedItems()
is the function attached to the onclick
event of the aforementioned button.
<script type="text/javascript">
window.page = 0;
function loadMoreFeedItems() {
var options = {};
options.page = window.page;
$.ajax({
url: "home/feed",
data: options,
dataType: "html",
success: function (data) {
// Code to append the data received into the feed element
window.page++;
// Code to hide "load more" button if window.page exceeds 10
}
});
}
(function () {
loadMoreFeedItems();
})();
</script>
So I did a little reading about global variables in JavaScript[1][2][3] and while this works, I got the vibe that this could be problematic, so I'm wondering if there is a better way. One alternative I thought of was to create some kind of hidden that stores the value in page rather than the browser, and then I'd modify/retrieve it using a jQuery selector, but that seems even dirtier.