@atlassian/aui
Version:
Atlassian User Interface library
51 lines (41 loc) • 1.61 kB
JavaScript
import Backbone from 'backbone';
import globalize from './internal/globalize';
var ResultSet = Backbone.Model.extend({
initialize: function (options) {
this.set('active', null, { silent: true });
this.collection = new Backbone.Collection();
this.collection.bind('reset', this.setActive, this);
this.source = options.source;
this.source.bind('respond', this.process, this);
},
url: false,
process: function (response) {
this.set('query', response.query);
this.collection.reset(response.results);
this.set('length', response.results.length);
this.trigger('update', this);
},
setActive: function () {
var id = arguments[0] instanceof Backbone.Collection ? false : arguments[0];
var model = id ? this.collection.get(id) : this.collection.first();
this.set('active', model || null);
return this.get('active');
},
next: function () {
var current = this.collection.indexOf(this.get('active'));
var i = (current + 1) % this.get('length');
var next = this.collection.at(i);
return this.setActive(next && next.id);
},
prev: function () {
var current = this.collection.indexOf(this.get('active'));
var i = (current === 0 ? this.get('length') : current) - 1;
var prev = this.collection.at(i);
return this.setActive(prev && prev.id);
},
each: function () {
return this.collection.each.apply(this.collection, arguments);
},
});
globalize('ResultSet', ResultSet);
export default ResultSet;