Skip to content

Instantly share code, notes, and snippets.

@edtoken
Created October 27, 2015 17:27
Show Gist options
  • Save edtoken/cade2501394fb99b6b01 to your computer and use it in GitHub Desktop.
Save edtoken/cade2501394fb99b6b01 to your computer and use it in GitHub Desktop.
import _ from 'underscore';
import Collection from 'core/Collection';
import MediaModel from 'storage/models/Media';
class MediaCollection extends Collection {
constructor(attr, options) {
options.model = MediaModel;
super(attr, options);
this.itemsOrder = []; // порядок медиафайлов в коллекции
this._itemsOrder = []; // предыдущий порядок
this.comparatorType = 'makeSortByOrderList';
}
comparator() {
var comp = this.comparatorType || 'makeSortByOrderList';
return this[comp].apply(this, arguments);
}
makeSortByOrderList(a, b) {
if (!this.itemsOrder || !this.itemsOrder.length) return 0;
var aIndex = this.itemsOrder.indexOf(a.id);
var bIndex = this.itemsOrder.indexOf(b.id);
// если модель не найдена в текущем массиве для сортировки
// ищу предыдущее положение
if (aIndex < 0) {
aIndex = this._itemsOrder.indexOf(a.id);
aIndex = (aIndex > this.itemsOrder.length) ? aIndex : this.itemsOrder.length + 1;
}
if (bIndex < 0) {
bIndex = this._itemsOrder.indexOf(b.id);
bIndex = (bIndex > this.itemsOrder.length) ? bIndex : this.itemsOrder.length + 1;
}
if (aIndex < 0) aIndex = this.itemsOrder.length + 1;
if (bIndex < 0) bIndex = this.itemsOrder.length + 1;
return aIndex > bIndex ? 1
: aIndex < bIndex ? -1
: 0;
}
sortByOrderList(ids) {
this._itemsOrder = this.itemsOrder.slice(0);
this.itemsOrder = ids;
this.comparatorType = 'makeSortByOrderList';
this.sort();
return this;
}
createSortOrder() {
this.itemsOrder = this.pluck('id');
this._itemsOrder = this.itemsOrder.slice(0);
return this;
}
}
module.exports = MediaCollection;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment