Last active
August 29, 2015 14:05
-
-
Save legastero/32d12cef5b3c9b37e15a to your computer and use it in GitHub Desktop.
Collection pager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In-progress experiments with this idea before making a proper module | |
var State = require('ampersand-state'); | |
module.exports = State.extend({ | |
props: { | |
max: ['number', true, 20], | |
reverse: 'boolean', | |
first: 'any', // string or bool (true means end-of-collection, false means start-of-collection) | |
last: 'string', | |
firstIndex: 'string', | |
count: 'number' | |
}, | |
initialize: function (spec) { | |
this.collection = spec.collection; | |
this.pageFetch = spec.fetch; | |
}, | |
next: function () { | |
if (this.reverse) { | |
this._fetch({ | |
max: this.max, | |
before: this.first || true | |
}); | |
} else { | |
this._fetch({ | |
max: this.max, | |
after: this.last | |
}); | |
} | |
}, | |
prev: function () { | |
if (this.reverse) { | |
this._fetch({ | |
max: this.max, | |
after: this.last | |
}); | |
} else { | |
this._fetch({ | |
max: this.max, | |
before: this.first | |
}); | |
} | |
}, | |
getPage: function (startingIndex) { | |
this._fetch({ | |
max: this.max, | |
index: startingIndex | |
}); | |
}, | |
getCount: function () { | |
this._fetch({ | |
max: 0 | |
}); | |
}, | |
_fetch: function (opts) { | |
var self = this; | |
this.pageFetch(opts, function (err, res) { | |
if (err) { | |
return self.trigger('error', self, err); | |
} | |
self.update(res.paging); | |
var method = res.reset ? 'reset' : 'set'; | |
self.collection[method](res.items); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
self.collection.reset(res.items);
– I'd leave a choice whether to reset collection or just add items to it to a user. This way it could be easily reused as infinite scrolling module as well.