A Simple Paginator
A Simple Paginator that works without priorities.
by Firebase
HTML
<script src="http://static.firebase.com/v0/firebase.js"></script>
<h3>A Simple Paginator</h3>
<div></div>
<button id="prev">prev 5</button>
<button id="next">next 5</button>
CSS
div {
padding: 20px;
font-size: 20px;
border-radius: 15px;
background-color: #fafafa;
border: 1px solid #999;
font-family:'Courier New', 'Courier', monospaced;
margin-bottom: 10px;
}
h3 {
clear: both;
padding-top: 20px;
}
button {
font-size: 36px;
}
}
JavaScript
/***************************
A SIMPLE PAGINATOR
*************************/
function Paginator(ref, limit) {
this.ref = ref;
this.pageNumber = 0;
this.limit = limit;
this.lastPageNumber = null;
this.currentSet = {};
}
Paginator.prototype = {
nextPage: function (callback) {
if( this.isLastPage() ) {
callback(this.currentSet);
}
else {
var lastKey = getLastKey(this.currentSet);
// if there is no last key, we need to use undefined as priority
var pri = lastKey ? null : undefined;
this.ref.startAt(pri, lastKey)
.limit(this.limit + (lastKey? 1 : 0))
.once('value', this._process.bind(this, {
cb: callback,
dir: 'next',
key: lastKey
}));
}
},
prevPage: function (callback) {
console.log('prevPage', this.isFirstPage(), this.pageNumber);
if( this.isFirstPage() ) {
callback(this.currentSet);
}
else {
var firstKey = getFirstKey(this.currentSet);
// if there is no last key, we need to use undefined as priority
this.ref.endAt(null, firstKey)
.limit(this.limit+1)
.once('value', this._process.bind(this, {
cb: callback,
dir: 'prev',
key: firstKey
}));
}
},
isFirstPage: function () {
return this.pageNumber === 1;
},
isLastPage: function () {
return this.pageNumber === this.lastPageNumber;
},
_process: function (opts, snap) {
var vals = snap.val(), len = size(vals);
console.log('_process', opts, len, this.pageNumber, vals);
if( len < this.limit ) {
// if the next page returned some results, it becomes the last page
// otherwise this one is
...