Skip to content

Instantly share code, notes, and snippets.

@davidmontoyago
Last active December 21, 2015 16:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davidmontoyago/6336612 to your computer and use it in GitHub Desktop.
Save davidmontoyago/6336612 to your computer and use it in GitHub Desktop.
Infinite scroll list view with Backbone.js - Got some inspiration from @kjantzer: https://gist.github.com/kjantzer/4021245
/**
* Extend for infinite scrolling capabilities.
*
* "addMore" function must be implemented in the child view.
* The infinite scrolling is disabled by default, must be enabled from the child view when initialized or ready.
*
* Uses jquery waypoints - http://imakewebthings.com/jquery-waypoints/
*
* Config options:
* - endOfList: id of the way-point element
* - loadingClass: class for loading indicator. The class is added to the waypoint element.
*
* @author David Montoya
* @version 1.0 - 3/4/13 - 11:22 AM
*/
InfiniteListView = Backbone.View.extend({
initialize: function() {
_.bindAll(this);
this.$endOfList = $(this.options.endOfList);
this.$endOfList.waypoint({
offset: '100%',
handler: _.bind(this.endReached, this),
enabled: false
});
},
/**
* When the end of this list is reached.
*/
endReached: function() {
this.onLoading();
// addMore in the child view is in charge of adding the content.
this.addMore(this.onComplete);
},
onLoading: function() {
// disables waypoints while it loads new content
this.disableScrolling();
if (this.options.loadingClass)
this.$endOfList.addClass(this.options.loadingClass);
},
onComplete: function() {
if (this.options.loadingClass)
this.$endOfList.removeClass(this.options.loadingClass);
this.enableScrolling();
},
enableScrolling: function() {
this.$endOfList.waypoint('enable');
$.waypoints('refresh');
},
disableScrolling: function(){
this.$endOfList.waypoint('disable');
$.waypoints('refresh');
}
});
/**
* Example of infinite scrolling view
*/
ExampleListView = InfiniteListView.extend({
initialize: function() {
_.bindAll(this);
this.collection.bind('reset', this.render);
// parent constructor - initialize infinite scrolling
InfiniteListView.prototype.initialize.call(this, this.options);
},
render: function() {
this.addAll();
},
addMore: function(onCompleteCallback) {
// onCompleteCallback notifies the parent view when it's ready to enable the waypoint
this.collection.fetch({
complete: onCompleteCallback
});
},
addAll: function() {
this.collection.each(this.addOne);
},
addOne: function(oneItem) {
var oneItemView = new OneItemView({
model: oneItem
});
this.$el.append(oneItemView.render().el);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment