开发者

Having some trouble with the logic in my Javascript pagination code

function Browse()
{
    this.o开发者_开发百科ffset = 10;
}

/*
 * @direction is either 'next' or 'prev'
 */
Browse.prototype.loadMore = function(direction)
{
    var _this = this;

    $.getJSON('/path/to/api?offset=' + this.offset, function(json)
    {
        _this.offset = (direction == 'next') ? _this.offset + 10 : _this.offset - 10;

        if (_this.offset > 10)
            previousButton.show();
        else
            previousButton.hide();
    });
}

This is the basic code. The user clicks a link which triggers loadMore(). This function pulls down the JSON data starting at the offset.

This offset will change based on their current 'page'. The first page will have a 0 offset. Second page will be 10. Third page 20, etc...

As they navigate back and forth, this offset should change accordingly. The problem is, it isn't. I can't see why...

Any ideas?


It's because the ajax call takes time to execute.

Try:

//...
var _this = this;

$.getJSON('/path/to/api?offset=' + this.offset, function(json) {
  //...
});
_this.offset = (direction == 'next') ? _this.offset + 10 : _this.offset - 10;
//...

This will use the right value in your ajax call, and change the offset ready for the next call before the ajax call returns. You might want to add logic to ignore the return value from the ajax call if the offset has been adjusted in the mean time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜