Skip to content

Commit

Permalink
Collection: Bugfix. Sort items before calling *:item events.
Browse files Browse the repository at this point in the history
  • Loading branch information
Ivo Sonderegger committed Nov 18, 2020
1 parent d10b386 commit 2556387
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/meteoJS/base/Collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,9 @@ export class Collection {
* @fires module:meteoJS/base/collection#replace:item
*/
append(...items) {
const addItem = [];
const removeItem = [];
const replaceItem = [];
items.forEach(item => {
let id = item.id;
if (this.containsId(id)) {
Expand All @@ -200,20 +203,23 @@ export class Collection {
if (itemInCollection !== item) {
this._items[id] = item;
if (this.options.fireReplace)
this.trigger('replace:item', item, itemInCollection);
replaceItem.push([item, itemInCollection]);
if (this.options.fireAddRemoveOnReplace) {
this.trigger('remove:item', itemInCollection);
this.trigger('add:item', item);
removeItem.push(itemInCollection);
addItem.push(item);
}
}
}
else {
this._itemIds.push(id);
this._items[id] = item;
this.trigger('add:item', item);
addItem.push(item);
}
});
this._sort();
addItem.forEach(item => this.trigger('add:item', item));
removeItem.forEach(item => this.trigger('remove:item', item));
replaceItem.forEach(([item, itemInCollection]) => this.trigger('replace:item', item, itemInCollection));
return this;
}

Expand Down
23 changes: 23 additions & 0 deletions test/meteoJS/base/collection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,29 @@ describe('Default collection, import via default', () => {
iteratorCount++;
assert.equal(iteratorCount, 4, 'iterator size');
});
it('sorted on *:item events', () => {
let counter = 0;
const coll = new Collection({
sortFunction: (a, b) => b.id.localeCompare(a.id)
});
coll.on('add:item', item => {
counter++;
let testIds = ['d', 'c', 'b', 'a'];
Array.from(coll)
.forEach(item => assert.equal(item.id, testIds.shift(), 'Sortierung innerhalb add:item'));
});
coll.append(a, b, c, d);
assert.equal(coll.count, 4);
assert.equal(coll.itemIds[0], 'd');
assert.equal(coll.itemIds[1], 'c');
assert.equal(coll.itemIds[2], 'b');
assert.equal(coll.itemIds[3], 'a');
for (const value of coll) {
assert.equal(value.id, 'd', 'iterator first element');
break;
}
assert.equal(counter, 4);
});
describe('remove tests', () => {
it('remove', () => {
let addCounter = 0;
Expand Down

0 comments on commit 2556387

Please sign in to comment.