Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite scroll backbone view

I would like to have an infinite/endless scroll data rendering from a JSON feed. I am interested in accomplishing something similar to Pinterest or Google Reader using Backbone/Underscore/jQuery.

How do I apply the infiniScroll.js module to my backbone view? The goal is to fetch and append the next page's ("page" URL parameter) tweets when you scroll near the end of the page. Problem: when reaching the bottom of page, same JSON page feed is fetched. How to change the page parameter in the URL to be &page=2, etc.

Demo: http://dl.dropbox.com/u/19974044/test.html OR http://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')
});​
like image 700
Steve Avatar asked Jun 01 '26 16:06

Steve


1 Answers

The url attribute can be specified as a function rather than a string. So you could replace it with something like this:

...
currentPage: 0,
url: function() {
  this.currentPage++;
  return 'https://path.to.url/?page=' + this.currentPage;
},
...
like image 108
Willson Haw Avatar answered Jun 04 '26 13:06

Willson Haw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!