diff --git a/src/meteoJS/base/Collection.js b/src/meteoJS/base/Collection.js index 7afbf068..edef2b93 100644 --- a/src/meteoJS/base/Collection.js +++ b/src/meteoJS/base/Collection.js @@ -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)) { @@ -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; } diff --git a/test/meteoJS/base/collection.test.js b/test/meteoJS/base/collection.test.js index ebe29a9d..8c3cc497 100644 --- a/test/meteoJS/base/collection.test.js +++ b/test/meteoJS/base/collection.test.js @@ -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;