This repository has been archived by the owner on Jul 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Backbone.InfiniteCollection.js
92 lines (79 loc) · 2.18 KB
/
Backbone.InfiniteCollection.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
Backbone.InfiniteCollection = Backbone.Collection.extend({
_index: 0,
pageSize: 1,
initialize: function(undefined, options) {
_.extend(this, options);
this.on('reset', function() { this._index = 0; }, this);
},
/**
* Returns the current page from left to right, wrapping around to the
* beginning if needed.
*/
getPage: function() {
var slice = this.slice(this._index, this._index + this.pageSize);
if (slice.length < this.pageSize) {
slice = slice.concat(this.slice(0, this.pageSize - slice.length));
}
return new Backbone.Collection(slice);
},
/**
* Retreats the index by pageSize, wrapping around to the end if needed.
*/
retreat: function() {
return this.setIndex(this._index - this.pageSize);
},
/**
* Returns the previous page *without* retreating the index.
*/
behind: function() {
var slice = this.retreat().getPage();
this.advance();
return slice;
},
/**
* Returns the previous page, retreating the index.
*/
previous: function() {
return this.retreat().getPage();
},
/**
* Advances the index by pageSize, wrapping around to the beginning if needed.
*/
advance: function() {
return this.setIndex(this._index + this.pageSize);
},
/**
* Returns the next page *without* advancing the index.
*/
ahead: function() {
var slice = this.advance().getPage();
this.retreat();
return slice;
},
/**
* Returns the next page, advancing the index. This is the page *after* the
* current page (that's what getPage() is for).
*/
next: function() {
return this.advance().getPage();
},
/**
* Sets the index directly, wrapping it as needed.
*
* This method will recurse to handle indexes that are far out of range.
* If the collection has 8 items, for example, and given index is -24, it'll
* keep calling itself, altering the index each time until it's within bounds.
*/
setIndex: function(index) {
if (index < 0) {
return this.setIndex(index + this.length);
}
else if (index >= this.length) {
return this.setIndex(index - this.length);
}
else {
this._index = index;
}
return this;
}
});