I have created the below function to bind to all the classes of type .wrapper in my page. The problem I have is that when I trigger any of these events, the var ‘this’ no longer points to the binding it’s particular loop, but rather the ‘this’ that was used in the final iteration of the looping bind. This seems like a mistake in my understanding of how var’s are stored at binding, rather than as a value, they are stored as pointers. Can anyone help to show me how I can make these binds remain relevant to their objects.
var pullUpEl, pullUpOffset, generatedCount = 0, index = 0, wrappers = [];
$('.wrapper').each(function () {
if ($(this).hasClass('tooltip')) {
pullUpEl = $(this)[0].getElementsByTagName("div")[0].getElementsByTagName("div")[0];
pullUpOffset = pullUpEl.offsetHeight;
wrappers[index] = new iScroll($(this).attr('id'), {
useTransition: true,
fadeScrollbar: true,
hideScrollbar: false,
hScrollbar: false,
//snap: 'li',
onRefresh: function () {
if (pullUpEl.className.match('loading')) {
pullUpEl.className = '';
pullUpEl.querySelector('.pullUpLabel').innerHTML = 'Pull up to load more...';
}
},
onScrollMove: function () {
if (this.y < (this.maxScrollY - 5) && !pullUpEl.className.match('flip')) {
pullUpEl.className = 'flip';
pullUpEl.querySelector('.pullUpLabel').innerHTML = 'Release to refresh...';
this.maxScrollY = this.maxScrollY;
} else if (this.y > (this.maxScrollY + 5) && pullUpEl.className.match('flip')) {
pullUpEl.className = '';
pullUpEl.querySelector('.pullUpLabel').innerHTML = 'Pull up to load more...';
this.maxScrollY = pullUpOffset;
}
},
onScrollEnd: function () {
if (pullUpEl.className.match('flip')) {
pullUpEl.className = 'loading';
pullUpEl.querySelector('.pullUpLabel').innerHTML = 'Loading...';
pullUpAction(this, pullUpEl.parentNode.getElementsByTagName("ul")[0]);
}
}
});
} else {
wrappers[index] = new iScroll($(this).attr('id'));
}
index++;
});
It’s not a problem with
this, it’s a problem withpullUpEl. You made this global, so it’s final value is the last element in the.each()block. When youronRefresh,onScrollMove, etc. functions are ran, they are not ran in the context wherepullUpElis actually changing. So, essentially, no matter which element triggers this, all the changes are run on the last element of the loop every time.