无限滚动骨干视图

时间:2012-10-01 18:48:20

标签: javascript jquery backbone.js underscore.js infinite-scroll

我希望从JSON提要中获得无限/无限滚动数据。我有兴趣使用Backbone / Underscore / jQuery完成与Pinterest或Google Reader类似的东西。

如何将infiniScroll.js模块应用到我的骨干网视图?目标是在靠近末尾滚动时获取并附加下一页的(“页面”网址参数)推文的页面。问题:到达页面底部时,将获取相同的JSON页面提要。如何将网址中的page参数更改为&page=2

演示: http://dl.dropbox.com/u/19974044/test.htmlhttp://jsfiddle.net/k4rPP/3/

// Define the model
Tweet = Backbone.Model.extend();

// Define the collection
Tweets = Backbone.Collection.extend({
    model: Tweet,
    // Url to request when fetch() is called
    url: 'https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&trim_user=false&count=10&screen_name=cnn&page=1&callback=?',
    parse: function (response) {
        return response;
    },
    // Overwrite the sync method to pass over the Same Origin Policy
    sync: function (method, model, options) {
        var that = this;
        var params = _.extend({
            type: 'GET',
            dataType: 'jsonp',
            url: that.url,
            processData: false
        }, options);

        return $.ajax(params);
    }
});

// Define the View
TweetsView = Backbone.View.extend({
    initialize: function () {
        _.bindAll(this, 'render');
        // create a collection
        this.collection = new Tweets;
        // Fetch the collection and call render() method
        var that = this;
        this.collection.fetch({
            success: function () {
                that.render();
            }
        });
        // infiniScroll.js integration
        this.infiniScroll = new Backbone.InfiniScroll(this.collection, {success: this.appendRender, param:'page', includePage:true});
    },
    // Use an extern template
    template: _.template($('#tweetsTemplate').html()),

    render: function () {
        // Fill the html with the template and the collection
        $(this.el).html(this.template({
            tweets: this.collection.toJSON()
        }));
    }
});

var app = new TweetsView({
    // define the el where the view will render
    el: $('body')
});​

1 个答案:

答案 0 :(得分:1)

url属性可以指定为函数而不是字符串。所以你可以用这样的东西代替它:

...
currentPage: 0,
url: function() {
  this.currentPage++;
  return 'https://path.to.url/?page=' + this.currentPage;
},
...