Forum Moderators: open

Message Too Old, No Replies

Storing a variable outside of a callback function

         

csdude55

2:10 am on May 24, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



In an infinite scroll, I'm using an Ajax fragment response that looks like this:

<script>
var startCount = 2;

function showData(x) {
alert(x);
}

function loadMore(listID) {
$(listID).append($('<div></div>')
.load($('example'), function() {
startCount += 2;

showData(startCount);
})
);
}


(I know, .load() is deprecated so I probably should change that soon)

If I increment startCount inside of the callback (like above), it remembers the value at each iteration of the infinite scroll, like I want. But if I move it to showData() (outside of the callback), it loses the value and starts back at 2 each iteration.

The problem is that I use the loadMore() function in several sections, and only one of them uses the startCount variable. So is there ANY way to move it outside of the callback function? Or will I have to resort to listing several variables inside of the callback function that may not be used each time?

Fotiman

3:05 pm on Jun 5, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You've got a global variable, startCount.

In the callback for your load function, you increment that global variable, then pass it to showData. Since startCount is global, it shouldn't matter if you increment it in the callback, or in showData:


var startCount = 2;
function showData() {
startCount += 2;
alert(startCount);
}

lucy24

9:26 pm on Jun 5, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



var startCount = 2;
What happens if you omit the "var" and proceed directly to
startCount = 2;
? I'm wondering if the script somehow thinks startCount is being redefined over and over again. (I realize the script should not think this, because global is global, but who knows what goes on in the mind of a browser.) And then, if it does behave differently, you're closer to figuring out what is going on.