Skip to content

Instantly share code, notes, and snippets.

@fcurella
Created January 9, 2011 18:06
Show Gist options
  • Save fcurella/771865 to your computer and use it in GitHub Desktop.
Save fcurella/771865 to your computer and use it in GitHub Desktop.
A Backbone.js collection class with utility methods for iterating and picking
IterableCollection = Backbone.Collection.extend({
initialize: function() {
//_.bindAll(this, )
this._resetIndexes();
},
_resetIndexes: function() {
this.currentIndex = 0;
this.hasSelection = false;
},
parse: function(response) {
return response.objects;
},
current: function() {
if (this.length < 1) return false;
return this.at(this.currentIndex);
},
hasPrev: function () {
if (this.length < 2) return false;
return this.at(this.currentIndex-1) != undefined;
},
hasNext: function() {
if (this.length < 2) return false;
return this.at(this.currentIndex+1) != undefined;
},
prev: function() {
if (this.hasPrev()) {
this.currentIndex--;
this.trigger('index:current:set');
return this.current();
};
return false;
},
next: function() {
if (this.hasNext()) {
this.currentIndex++;
this.trigger('index:current:set');
return this.current();
};
return false;
},
restart: function() {
this._resetIndexes();
this.trigger('index:restart');
this.trigger('index:current:set');
this.trigger('selection:restart');
this.trigger('selection:unset');
},
prevRound: function() {
if (this.hasPrev()) {
this.currentIndex--;
} else {
this.currentIndex = this.length-1;
};
this.trigger('index:current:set');
return this.current();
},
nextRound: function() {
if (this.hasNext()) {
this.currentIndex++;
} else {
this.currentIndex = 0;
};
this.trigger('index:current:set');
return this.current();
},
seek: function(index) {
this.hasSelection = true;
this.currentIndex = index;
this.trigger('selection');
this.trigger('selection:set');
this.trigger('index:current:set');
return this.current();
},
seekModel: function(model) {
index = this.indexOf(model);
return this.seek(index);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment