Debian Codegraph @

test/collection.js

raw
1 (function(QUnit) {
2
3 var a, b, c, d, e, col, otherCol;
4
5 QUnit.module('Backbone.Collection', {
6
7 beforeEach: function(assert) {
8 a = new Backbone.Model({id: 3, label: 'a'});
9 b = new Backbone.Model({id: 2, label: 'b'});
10 c = new Backbone.Model({id: 1, label: 'c'});
11 d = new Backbone.Model({id: 0, label: 'd'});
12 e = null;
13 col = new Backbone.Collection([a, b, c, d]);
14 otherCol = new Backbone.Collection();
15 }
16
17 });
18
19 QUnit.test('new and sort', function(assert) {
20 assert.expect(6);
21 var counter = 0;
22 col.on('sort', function(){ counter++; });
23 assert.deepEqual(col.pluck('label'), ['a', 'b', 'c', 'd']);
24 col.comparator = function(m1, m2) {
25 return m1.id > m2.id ? -1 : 1;
26 };
27 col.sort();
28 assert.equal(counter, 1);
29 assert.deepEqual(col.pluck('label'), ['a', 'b', 'c', 'd']);
30 col.comparator = function(model) { return model.id; };
31 col.sort();
32 assert.equal(counter, 2);
33 assert.deepEqual(col.pluck('label'), ['d', 'c', 'b', 'a']);
34 assert.equal(col.length, 4);
35 });
36
37 QUnit.test('String comparator.', function(assert) {
38 assert.expect(1);
39 var collection = new Backbone.Collection([
40 {id: 3},
41 {id: 1},
42 {id: 2}
43 ], {comparator: 'id'});
44 assert.deepEqual(collection.pluck('id'), [1, 2, 3]);
45 });
46
47 QUnit.test('new and parse', function(assert) {
48 assert.expect(3);
49 var Collection = Backbone.Collection.extend({
50 parse: function(data) {
51 return _.filter(data, function(datum) {
52 return datum.a % 2 === 0;
53 });
54 }
55 });
56 var models = [{a: 1}, {a: 2}, {a: 3}, {a: 4}];
57 var collection = new Collection(models, {parse: true});
58 assert.strictEqual(collection.length, 2);
59 assert.strictEqual(collection.first().get('a'), 2);
60 assert.strictEqual(collection.last().get('a'), 4);
61 });
62
63 QUnit.test('clone preserves model and comparator', function(assert) {
64 assert.expect(3);
65 var Model = Backbone.Model.extend();
66 var comparator = function(model){ return model.id; };
67
68 var collection = new Backbone.Collection([{id: 1}], {
69 model: Model,
70 comparator: comparator
71 }).clone();
72 collection.add({id: 2});
73 assert.ok(collection.at(0) instanceof Model);
74 assert.ok(collection.at(1) instanceof Model);
75 assert.strictEqual(collection.comparator, comparator);
76 });
77
78 QUnit.test('get', function(assert) {
79 assert.expect(6);
80 assert.equal(col.get(0), d);
81 assert.equal(col.get(d.clone()), d);
82 assert.equal(col.get(2), b);
83 assert.equal(col.get({id: 1}), c);
84 assert.equal(col.get(c.clone()), c);
85 assert.equal(col.get(col.first().cid), col.first());
86 });
87
88 QUnit.test('get with non-default ids', function(assert) {
89 assert.expect(5);
90 var MongoModel = Backbone.Model.extend({idAttribute: '_id'});
91 var model = new MongoModel({_id: 100});
92 var collection = new Backbone.Collection([model], {model: MongoModel});
93 assert.equal(collection.get(100), model);
94 assert.equal(collection.get(model.cid), model);
95 assert.equal(collection.get(model), model);
96 assert.equal(collection.get(101), void 0);
97
98 var collection2 = new Backbone.Collection();
99 collection2.model = MongoModel;
100 collection2.add(model.attributes);
101 assert.equal(collection2.get(model.clone()), collection2.first());
102 });
103
104 QUnit.test('has', function(assert) {
105 assert.expect(15);
106 assert.ok(col.has(a));
107 assert.ok(col.has(b));
108 assert.ok(col.has(c));
109 assert.ok(col.has(d));
110 assert.ok(col.has(a.id));
111 assert.ok(col.has(b.id));
112 assert.ok(col.has(c.id));
113 assert.ok(col.has(d.id));
114 assert.ok(col.has(a.cid));
115 assert.ok(col.has(b.cid));
116 assert.ok(col.has(c.cid));
117 assert.ok(col.has(d.cid));
118 var outsider = new Backbone.Model({id: 4});
119 assert.notOk(col.has(outsider));
120 assert.notOk(col.has(outsider.id));
121 assert.notOk(col.has(outsider.cid));
122 });
123
124 QUnit.test('update index when id changes', function(assert) {
125 assert.expect(6);
126 var collection = new Backbone.Collection();
127 collection.add([
128 {id: 0, name: 'one'},
129 {id: 1, name: 'two'}
130 ]);
131 var one = collection.get(0);
132 assert.equal(one.get('name'), 'one');
133 collection.on('change:name', function(model) {
134 assert.ok(this.get(model));
135 assert.equal(model, this.get(101));
136 assert.equal(this.get(0), null);
137 });
138 one.set({name: 'dalmatians', id: 101});
139 assert.equal(collection.get(0), null);
140 assert.equal(collection.get(101).get('name'), 'dalmatians');
141 });
142
143 QUnit.test('at', function(assert) {
144 assert.expect(2);
145 assert.equal(col.at(2), c);
146 assert.equal(col.at(-2), c);
147 });
148
149 QUnit.test('pluck', function(assert) {
150 assert.expect(1);
151 assert.equal(col.pluck('label').join(' '), 'a b c d');
152 });
153
154 QUnit.test('add', function(assert) {
155 assert.expect(14);
156 var added, opts, secondAdded;
157 added = opts = secondAdded = null;
158 e = new Backbone.Model({id: 10, label: 'e'});
159 otherCol.add(e);
160 otherCol.on('add', function() {
161 secondAdded = true;
162 });
163 col.on('add', function(model, collection, options){
164 added = model.get('label');
165 opts = options;
166 });
167 col.add(e, {amazing: true});
168 assert.equal(added, 'e');
169 assert.equal(col.length, 5);
170 assert.equal(col.last(), e);
171 assert.equal(otherCol.length, 1);
172 assert.equal(secondAdded, null);
173 assert.ok(opts.amazing);
174
175 var f = new Backbone.Model({id: 20, label: 'f'});
176 var g = new Backbone.Model({id: 21, label: 'g'});
177 var h = new Backbone.Model({id: 22, label: 'h'});
178 var atCol = new Backbone.Collection([f, g, h]);
179 assert.equal(atCol.length, 3);
180 atCol.add(e, {at: 1});
181 assert.equal(atCol.length, 4);
182 assert.equal(atCol.at(1), e);
183 assert.equal(atCol.last(), h);
184
185 var coll = new Backbone.Collection(new Array(2));
186 var addCount = 0;
187 coll.on('add', function(){
188 addCount += 1;
189 });
190 coll.add([undefined, f, g]);
191 assert.equal(coll.length, 5);
192 assert.equal(addCount, 3);
193 coll.add(new Array(4));
194 assert.equal(coll.length, 9);
195 assert.equal(addCount, 7);
196 });
197
198 QUnit.test('add multiple models', function(assert) {
199 assert.expect(6);
200 var collection = new Backbone.Collection([{at: 0}, {at: 1}, {at: 9}]);
201 collection.add([{at: 2}, {at: 3}, {at: 4}, {at: 5}, {at: 6}, {at: 7}, {at: 8}], {at: 2});
202 for (var i = 0; i <= 5; i++) {
203 assert.equal(collection.at(i).get('at'), i);
204 }
205 });
206
207 QUnit.test('add; at should have preference over comparator', function(assert) {
208 assert.expect(1);
209 var Col = Backbone.Collection.extend({
210 comparator: function(m1, m2) {
211 return m1.id > m2.id ? -1 : 1;
212 }
213 });
214
215 var collection = new Col([{id: 2}, {id: 3}]);
216 collection.add(new Backbone.Model({id: 1}), {at: 1});
217
218 assert.equal(collection.pluck('id').join(' '), '3 1 2');
219 });
220
221 QUnit.test('add; at should add to the end if the index is out of bounds', function(assert) {
222 assert.expect(1);
223 var collection = new Backbone.Collection([{id: 2}, {id: 3}]);
224 collection.add(new Backbone.Model({id: 1}), {at: 5});
225
226 assert.equal(collection.pluck('id').join(' '), '2 3 1');
227 });
228
229 QUnit.test("can't add model to collection twice", function(assert) {
230 var collection = new Backbone.Collection([{id: 1}, {id: 2}, {id: 1}, {id: 2}, {id: 3}]);
231 assert.equal(collection.pluck('id').join(' '), '1 2 3');
232 });
233
234 QUnit.test("can't add different model with same id to collection twice", function(assert) {
235 assert.expect(1);
236 var collection = new Backbone.Collection;
237 collection.unshift({id: 101});
238 collection.add({id: 101});
239 assert.equal(collection.length, 1);
240 });
241
242 QUnit.test('merge in duplicate models with {merge: true}', function(assert) {
243 assert.expect(3);
244 var collection = new Backbone.Collection;
245 collection.add([{id: 1, name: 'Moe'}, {id: 2, name: 'Curly'}, {id: 3, name: 'Larry'}]);
246 collection.add({id: 1, name: 'Moses'});
247 assert.equal(collection.first().get('name'), 'Moe');
248 collection.add({id: 1, name: 'Moses'}, {merge: true});
249 assert.equal(collection.first().get('name'), 'Moses');
250 collection.add({id: 1, name: 'Tim'}, {merge: true, silent: true});
251 assert.equal(collection.first().get('name'), 'Tim');
252 });
253
254 QUnit.test('add model to multiple collections', function(assert) {
255 assert.expect(10);
256 var counter = 0;
257 var m = new Backbone.Model({id: 10, label: 'm'});
258 m.on('add', function(model, collection) {
259 counter++;
260 assert.equal(m, model);
261 if (counter > 1) {
262 assert.equal(collection, col2);
263 } else {
264 assert.equal(collection, col1);
265 }
266 });
267 var col1 = new Backbone.Collection([]);
268 col1.on('add', function(model, collection) {
269 assert.equal(m, model);
270 assert.equal(col1, collection);
271 });
272 var col2 = new Backbone.Collection([]);
273 col2.on('add', function(model, collection) {
274 assert.equal(m, model);
275 assert.equal(col2, collection);
276 });
277 col1.add(m);
278 assert.equal(m.collection, col1);
279 col2.add(m);
280 assert.equal(m.collection, col1);
281 });
282
283 QUnit.test('add model with parse', function(assert) {
284 assert.expect(1);
285 var Model = Backbone.Model.extend({
286 parse: function(obj) {
287 obj.value += 1;
288 return obj;
289 }
290 });
291
292 var Col = Backbone.Collection.extend({model: Model});
293 var collection = new Col;
294 collection.add({value: 1}, {parse: true});
295 assert.equal(collection.at(0).get('value'), 2);
296 });
297
298 QUnit.test('add with parse and merge', function(assert) {
299 var collection = new Backbone.Collection();
300 collection.parse = function(attrs) {
301 return _.map(attrs, function(model) {
302 if (model.model) return model.model;
303 return model;
304 });
305 };
306 collection.add({id: 1});
307 collection.add({model: {id: 1, name: 'Alf'}}, {parse: true, merge: true});
308 assert.equal(collection.first().get('name'), 'Alf');
309 });
310
311 QUnit.test('add model to collection with sort()-style comparator', function(assert) {
312 assert.expect(3);
313 var collection = new Backbone.Collection;
314 collection.comparator = function(m1, m2) {
315 return m1.get('name') < m2.get('name') ? -1 : 1;
316 };
317 var tom = new Backbone.Model({name: 'Tom'});
318 var rob = new Backbone.Model({name: 'Rob'});
319 var tim = new Backbone.Model({name: 'Tim'});
320 collection.add(tom);
321 collection.add(rob);
322 collection.add(tim);
323 assert.equal(collection.indexOf(rob), 0);
324 assert.equal(collection.indexOf(tim), 1);
325 assert.equal(collection.indexOf(tom), 2);
326 });
327
328 QUnit.test('comparator that depends on `this`', function(assert) {
329 assert.expect(2);
330 var collection = new Backbone.Collection;
331 collection.negative = function(num) {
332 return -num;
333 };
334 collection.comparator = function(model) {
335 return this.negative(model.id);
336 };
337 collection.add([{id: 1}, {id: 2}, {id: 3}]);
338 assert.deepEqual(collection.pluck('id'), [3, 2, 1]);
339 collection.comparator = function(m1, m2) {
340 return this.negative(m2.id) - this.negative(m1.id);
341 };
342 collection.sort();
343 assert.deepEqual(collection.pluck('id'), [1, 2, 3]);
344 });
345
346 QUnit.test('remove', function(assert) {
347 assert.expect(12);
348 var removed = null;
349 var result = null;
350 col.on('remove', function(model, collection, options) {
351 removed = model.get('label');
352 assert.equal(options.index, 3);
353 assert.equal(collection.get(model), undefined, '#3693: model cannot be fetched from collection');
354 });
355 result = col.remove(d);
356 assert.equal(removed, 'd');
357 assert.strictEqual(result, d);
358 //if we try to remove d again, it's not going to actually get removed
359 result = col.remove(d);
360 assert.strictEqual(result, undefined);
361 assert.equal(col.length, 3);
362 assert.equal(col.first(), a);
363 col.off();
364 result = col.remove([c, d]);
365 assert.equal(result.length, 1, 'only returns removed models');
366 assert.equal(result[0], c, 'only returns removed models');
367 result = col.remove([c, b]);
368 assert.equal(result.length, 1, 'only returns removed models');
369 assert.equal(result[0], b, 'only returns removed models');
370 result = col.remove([]);
371 assert.deepEqual(result, [], 'returns empty array when nothing removed');
372 });
373
374 QUnit.test('add and remove return values', function(assert) {
375 assert.expect(13);
376 var Even = Backbone.Model.extend({
377 validate: function(attrs) {
378 if (attrs.id % 2 !== 0) return 'odd';
379 }
380 });
381 var collection = new Backbone.Collection;
382 collection.model = Even;
383
384 var list = collection.add([{id: 2}, {id: 4}], {validate: true});
385 assert.equal(list.length, 2);
386 assert.ok(list[0] instanceof Backbone.Model);
387 assert.equal(list[1], collection.last());
388 assert.equal(list[1].get('id'), 4);
389
390 list = collection.add([{id: 3}, {id: 6}], {validate: true});
391 assert.equal(collection.length, 3);
392 assert.equal(list[0], false);
393 assert.equal(list[1].get('id'), 6);
394
395 var result = collection.add({id: 6});
396 assert.equal(result.cid, list[1].cid);
397
398 result = collection.remove({id: 6});
399 assert.equal(collection.length, 2);
400 assert.equal(result.id, 6);
401
402 list = collection.remove([{id: 2}, {id: 8}]);
403 assert.equal(collection.length, 1);
404 assert.equal(list[0].get('id'), 2);
405 assert.equal(list[1], null);
406 });
407
408 QUnit.test('shift and pop', function(assert) {
409 assert.expect(2);
410 var collection = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
411 assert.equal(collection.shift().get('a'), 'a');
412 assert.equal(collection.pop().get('c'), 'c');
413 });
414
415 QUnit.test('slice', function(assert) {
416 assert.expect(2);
417 var collection = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
418 var array = collection.slice(1, 3);
419 assert.equal(array.length, 2);
420 assert.equal(array[0].get('b'), 'b');
421 });
422
423 QUnit.test('events are unbound on remove', function(assert) {
424 assert.expect(3);
425 var counter = 0;
426 var dj = new Backbone.Model();
427 var emcees = new Backbone.Collection([dj]);
428 emcees.on('change', function(){ counter++; });
429 dj.set({name: 'Kool'});
430 assert.equal(counter, 1);
431 emcees.reset([]);
432 assert.equal(dj.collection, undefined);
433 dj.set({name: 'Shadow'});
434 assert.equal(counter, 1);
435 });
436
437 QUnit.test('remove in multiple collections', function(assert) {
438 assert.expect(7);
439 var modelData = {
440 id: 5,
441 title: 'Othello'
442 };
443 var passed = false;
444 var m1 = new Backbone.Model(modelData);
445 var m2 = new Backbone.Model(modelData);
446 m2.on('remove', function() {
447 passed = true;
448 });
449 var col1 = new Backbone.Collection([m1]);
450 var col2 = new Backbone.Collection([m2]);
451 assert.notEqual(m1, m2);
452 assert.ok(col1.length === 1);
453 assert.ok(col2.length === 1);
454 col1.remove(m1);
455 assert.equal(passed, false);
456 assert.ok(col1.length === 0);
457 col2.remove(m1);
458 assert.ok(col2.length === 0);
459 assert.equal(passed, true);
460 });
461
462 QUnit.test('remove same model in multiple collection', function(assert) {
463 assert.expect(16);
464 var counter = 0;
465 var m = new Backbone.Model({id: 5, title: 'Othello'});
466 m.on('remove', function(model, collection) {
467 counter++;
468 assert.equal(m, model);
469 if (counter > 1) {
470 assert.equal(collection, col1);
471 } else {
472 assert.equal(collection, col2);
473 }
474 });
475 var col1 = new Backbone.Collection([m]);
476 col1.on('remove', function(model, collection) {
477 assert.equal(m, model);
478 assert.equal(col1, collection);
479 });
480 var col2 = new Backbone.Collection([m]);
481 col2.on('remove', function(model, collection) {
482 assert.equal(m, model);
483 assert.equal(col2, collection);
484 });
485 assert.equal(col1, m.collection);
486 col2.remove(m);
487 assert.ok(col2.length === 0);
488 assert.ok(col1.length === 1);
489 assert.equal(counter, 1);
490 assert.equal(col1, m.collection);
491 col1.remove(m);
492 assert.equal(null, m.collection);
493 assert.ok(col1.length === 0);
494 assert.equal(counter, 2);
495 });
496
497 QUnit.test('model destroy removes from all collections', function(assert) {
498 assert.expect(3);
499 var m = new Backbone.Model({id: 5, title: 'Othello'});
500 m.sync = function(method, model, options) { options.success(); };
501 var col1 = new Backbone.Collection([m]);
502 var col2 = new Backbone.Collection([m]);
503 m.destroy();
504 assert.ok(col1.length === 0);
505 assert.ok(col2.length === 0);
506 assert.equal(undefined, m.collection);
507 });
508
509 QUnit.test('Collection: non-persisted model destroy removes from all collections', function(assert) {
510 assert.expect(3);
511 var m = new Backbone.Model({title: 'Othello'});
512 m.sync = function(method, model, options) { throw 'should not be called'; };
513 var col1 = new Backbone.Collection([m]);
514 var col2 = new Backbone.Collection([m]);
515 m.destroy();
516 assert.ok(col1.length === 0);
517 assert.ok(col2.length === 0);
518 assert.equal(undefined, m.collection);
519 });
520
521 QUnit.test('fetch', function(assert) {
522 assert.expect(4);
523 var collection = new Backbone.Collection;
524 collection.url = '/test';
525 collection.fetch();
526 assert.equal(this.syncArgs.method, 'read');
527 assert.equal(this.syncArgs.model, collection);
528 assert.equal(this.syncArgs.options.parse, true);
529
530 collection.fetch({parse: false});
531 assert.equal(this.syncArgs.options.parse, false);
532 });
533
534 QUnit.test('fetch with an error response triggers an error event', function(assert) {
535 assert.expect(1);
536 var collection = new Backbone.Collection();
537 collection.on('error', function() {
538 assert.ok(true);
539 });
540 collection.sync = function(method, model, options) { options.error(); };
541 collection.fetch();
542 });
543
544 QUnit.test('#3283 - fetch with an error response calls error with context', function(assert) {
545 assert.expect(1);
546 var collection = new Backbone.Collection();
547 var obj = {};
548 var options = {
549 context: obj,
550 error: function() {
551 assert.equal(this, obj);
552 }
553 };
554 collection.sync = function(method, model, opts) {
555 opts.error.call(opts.context);
556 };
557 collection.fetch(options);
558 });
559
560 QUnit.test('ensure fetch only parses once', function(assert) {
561 assert.expect(1);
562 var collection = new Backbone.Collection;
563 var counter = 0;
564 collection.parse = function(models) {
565 counter++;
566 return models;
567 };
568 collection.url = '/test';
569 collection.fetch();
570 this.syncArgs.options.success([]);
571 assert.equal(counter, 1);
572 });
573
574 QUnit.test('create', function(assert) {
575 assert.expect(4);
576 var collection = new Backbone.Collection;
577 collection.url = '/test';
578 var model = collection.create({label: 'f'}, {wait: true});
579 assert.equal(this.syncArgs.method, 'create');
580 assert.equal(this.syncArgs.model, model);
581 assert.equal(model.get('label'), 'f');
582 assert.equal(model.collection, collection);
583 });
584
585 QUnit.test('create with validate:true enforces validation', function(assert) {
586 assert.expect(3);
587 var ValidatingModel = Backbone.Model.extend({
588 validate: function(attrs) {
589 return 'fail';
590 }
591 });
592 var ValidatingCollection = Backbone.Collection.extend({
593 model: ValidatingModel
594 });
595 var collection = new ValidatingCollection();
596 collection.on('invalid', function(coll, error, options) {
597 assert.equal(error, 'fail');
598 assert.equal(options.validationError, 'fail');
599 });
600 assert.equal(collection.create({foo: 'bar'}, {validate: true}), false);
601 });
602
603 QUnit.test('create will pass extra options to success callback', function(assert) {
604 assert.expect(1);
605 var Model = Backbone.Model.extend({
606 sync: function(method, model, options) {
607 _.extend(options, {specialSync: true});
608 return Backbone.Model.prototype.sync.call(this, method, model, options);
609 }
610 });
611
612 var Collection = Backbone.Collection.extend({
613 model: Model,
614 url: '/test'
615 });
616
617 var collection = new Collection;
618
619 var success = function(model, response, options) {
620 assert.ok(options.specialSync, 'Options were passed correctly to callback');
621 };
622
623 collection.create({}, {success: success});
624 this.ajaxSettings.success();
625 });
626
627 QUnit.test('create with wait:true should not call collection.parse', function(assert) {
628 assert.expect(0);
629 var Collection = Backbone.Collection.extend({
630 url: '/test',
631 parse: function() {
632 assert.ok(false);
633 }
634 });
635
636 var collection = new Collection;
637
638 collection.create({}, {wait: true});
639 this.ajaxSettings.success();
640 });
641
642 QUnit.test('a failing create returns model with errors', function(assert) {
643 var ValidatingModel = Backbone.Model.extend({
644 validate: function(attrs) {
645 return 'fail';
646 }
647 });
648 var ValidatingCollection = Backbone.Collection.extend({
649 model: ValidatingModel
650 });
651 var collection = new ValidatingCollection();
652 var m = collection.create({foo: 'bar'});
653 assert.equal(m.validationError, 'fail');
654 assert.equal(collection.length, 1);
655 });
656
657 QUnit.test('initialize', function(assert) {
658 assert.expect(1);
659 var Collection = Backbone.Collection.extend({
660 initialize: function() {
661 this.one = 1;
662 }
663 });
664 var coll = new Collection;
665 assert.equal(coll.one, 1);
666 });
667
668 QUnit.test('preinitialize', function(assert) {
669 assert.expect(1);
670 var Collection = Backbone.Collection.extend({
671 preinitialize: function() {
672 this.one = 1;
673 }
674 });
675 var coll = new Collection;
676 assert.equal(coll.one, 1);
677 });
678
679 QUnit.test('preinitialize occurs before the collection is set up', function(assert) {
680 assert.expect(2);
681 var Collection = Backbone.Collection.extend({
682 preinitialize: function() {
683 assert.notEqual(this.model, FooModel);
684 }
685 });
686 var FooModel = Backbone.Model.extend({id: 'foo'});
687 var coll = new Collection({}, {
688 model: FooModel
689 });
690 assert.equal(coll.model, FooModel);
691 });
692
693 QUnit.test('toJSON', function(assert) {
694 assert.expect(1);
695 assert.equal(JSON.stringify(col), '[{"id":3,"label":"a"},{"id":2,"label":"b"},{"id":1,"label":"c"},{"id":0,"label":"d"}]');
696 });
697
698 QUnit.test('where and findWhere', function(assert) {
699 assert.expect(8);
700 var model = new Backbone.Model({a: 1});
701 var coll = new Backbone.Collection([
702 model,
703 {a: 1},
704 {a: 1, b: 2},
705 {a: 2, b: 2},
706 {a: 3}
707 ]);
708 assert.equal(coll.where({a: 1}).length, 3);
709 assert.equal(coll.where({a: 2}).length, 1);
710 assert.equal(coll.where({a: 3}).length, 1);
711 assert.equal(coll.where({b: 1}).length, 0);
712 assert.equal(coll.where({b: 2}).length, 2);
713 assert.equal(coll.where({a: 1, b: 2}).length, 1);
714 assert.equal(coll.findWhere({a: 1}), model);
715 assert.equal(coll.findWhere({a: 4}), void 0);
716 });
717
718 QUnit.test('mixin', function(assert) {
719 Backbone.Collection.mixin({
720 sum: function(models, iteratee) {
721 return _.reduce(models, function(s, m) {
722 return s + iteratee(m);
723 }, 0);
724 }
725 });
726
727 var coll = new Backbone.Collection([
728 {a: 1},
729 {a: 1, b: 2},
730 {a: 2, b: 2},
731 {a: 3}
732 ]);
733
734 assert.equal(coll.sum(function(m) {
735 return m.get('a');
736 }), 7);
737 });
738
739 QUnit.test('Underscore methods', function(assert) {
740 assert.expect(21);
741 assert.equal(col.map(function(model){ return model.get('label'); }).join(' '), 'a b c d');
742 assert.equal(col.some(function(model){ return model.id === 100; }), false);
743 assert.equal(col.some(function(model){ return model.id === 0; }), true);
744 assert.equal(col.reduce(function(m1, m2) {return m1.id > m2.id ? m1 : m2;}).id, 3);
745 assert.equal(col.reduceRight(function(m1, m2) {return m1.id > m2.id ? m1 : m2;}).id, 3);
746 assert.equal(col.indexOf(b), 1);
747 assert.equal(col.size(), 4);
748 assert.equal(col.rest().length, 3);
749 assert.ok(!_.includes(col.rest(), a));
750 assert.ok(_.includes(col.rest(), d));
751 assert.ok(!col.isEmpty());
752 assert.ok(!_.includes(col.without(d), d));
753
754 var wrapped = col.chain();
755 assert.equal(wrapped.map('id').max().value(), 3);
756 assert.equal(wrapped.map('id').min().value(), 0);
757 assert.deepEqual(
758 wrapped
759 .filter(function(o){ return o.id % 2 === 0; })
760 .map(function(o){ return o.id * 2; })
761 .value(),
762 [4, 0]
763 );
764 assert.deepEqual(col.difference([c, d]), [a, b]);
765 assert.ok(col.includes(col.sample()));
766
767 var first = col.first();
768 assert.deepEqual(col.groupBy(function(model){ return model.id; })[first.id], [first]);
769 assert.deepEqual(col.countBy(function(model){ return model.id; }), {0: 1, 1: 1, 2: 1, 3: 1});
770 assert.deepEqual(col.sortBy(function(model){ return model.id; })[0], col.at(3));
771 assert.ok(col.indexBy('id')[first.id] === first);
772 });
773
774 QUnit.test('Underscore methods with object-style and property-style iteratee', function(assert) {
775 assert.expect(26);
776 var model = new Backbone.Model({a: 4, b: 1, e: 3});
777 var coll = new Backbone.Collection([
778 {a: 1, b: 1},
779 {a: 2, b: 1, c: 1},
780 {a: 3, b: 1},
781 model
782 ]);
783 assert.equal(coll.find({a: 0}), undefined);
784 assert.deepEqual(coll.find({a: 4}), model);
785 assert.equal(coll.find('d'), undefined);
786 assert.deepEqual(coll.find('e'), model);
787 assert.equal(coll.filter({a: 0}), false);
788 assert.deepEqual(coll.filter({a: 4}), [model]);
789 assert.equal(coll.some({a: 0}), false);
790 assert.equal(coll.some({a: 1}), true);
791 assert.equal(coll.reject({a: 0}).length, 4);
792 assert.deepEqual(coll.reject({a: 4}), _.without(coll.models, model));
793 assert.equal(coll.every({a: 0}), false);
794 assert.equal(coll.every({b: 1}), true);
795 assert.deepEqual(coll.partition({a: 0})[0], []);
796 assert.deepEqual(coll.partition({a: 0})[1], coll.models);
797 assert.deepEqual(coll.partition({a: 4})[0], [model]);
798 assert.deepEqual(coll.partition({a: 4})[1], _.without(coll.models, model));
799 assert.deepEqual(coll.map({a: 2}), [false, true, false, false]);
800 assert.deepEqual(coll.map('a'), [1, 2, 3, 4]);
801 assert.deepEqual(coll.sortBy('a')[3], model);
802 assert.deepEqual(coll.sortBy('e')[0], model);
803 assert.deepEqual(coll.countBy({a: 4}), {'false': 3, 'true': 1});
804 assert.deepEqual(coll.countBy('d'), {undefined: 4});
805 assert.equal(coll.findIndex({b: 1}), 0);
806 assert.equal(coll.findIndex({b: 9}), -1);
807 assert.equal(coll.findLastIndex({b: 1}), 3);
808 assert.equal(coll.findLastIndex({b: 9}), -1);
809 });
810
811 QUnit.test('reset', function(assert) {
812 assert.expect(16);
813
814 var resetCount = 0;
815 var models = col.models;
816 col.on('reset', function() { resetCount += 1; });
817 col.reset([]);
818 assert.equal(resetCount, 1);
819 assert.equal(col.length, 0);
820 assert.equal(col.last(), null);
821 col.reset(models);
822 assert.equal(resetCount, 2);
823 assert.equal(col.length, 4);
824 assert.equal(col.last(), d);
825 col.reset(_.map(models, function(m){ return m.attributes; }));
826 assert.equal(resetCount, 3);
827 assert.equal(col.length, 4);
828 assert.ok(col.last() !== d);
829 assert.ok(_.isEqual(col.last().attributes, d.attributes));
830 col.reset();
831 assert.equal(col.length, 0);
832 assert.equal(resetCount, 4);
833
834 var f = new Backbone.Model({id: 20, label: 'f'});
835 col.reset([undefined, f]);
836 assert.equal(col.length, 2);
837 assert.equal(resetCount, 5);
838
839 col.reset(new Array(4));
840 assert.equal(col.length, 4);
841 assert.equal(resetCount, 6);
842 });
843
844 QUnit.test('reset with different values', function(assert) {
845 var collection = new Backbone.Collection({id: 1});
846 collection.reset({id: 1, a: 1});
847 assert.equal(collection.get(1).get('a'), 1);
848 });
849
850 QUnit.test('same references in reset', function(assert) {
851 var model = new Backbone.Model({id: 1});
852 var collection = new Backbone.Collection({id: 1});
853 collection.reset(model);
854 assert.equal(collection.get(1), model);
855 });
856
857 QUnit.test('reset passes caller options', function(assert) {
858 assert.expect(3);
859 var Model = Backbone.Model.extend({
860 initialize: function(attrs, options) {
861 this.modelParameter = options.modelParameter;
862 }
863 });
864 var collection = new (Backbone.Collection.extend({model: Model}))();
865 collection.reset([{astring: 'green', anumber: 1}, {astring: 'blue', anumber: 2}], {modelParameter: 'model parameter'});
866 assert.equal(collection.length, 2);
867 collection.each(function(model) {
868 assert.equal(model.modelParameter, 'model parameter');
869 });
870 });
871
872 QUnit.test('reset does not alter options by reference', function(assert) {
873 assert.expect(2);
874 var collection = new Backbone.Collection([{id: 1}]);
875 var origOpts = {};
876 collection.on('reset', function(coll, opts){
877 assert.equal(origOpts.previousModels, undefined);
878 assert.equal(opts.previousModels[0].id, 1);
879 });
880 collection.reset([], origOpts);
881 });
882
883 QUnit.test('trigger custom events on models', function(assert) {
884 assert.expect(1);
885 var fired = null;
886 a.on('custom', function() { fired = true; });
887 a.trigger('custom');
888 assert.equal(fired, true);
889 });
890
891 QUnit.test('add does not alter arguments', function(assert) {
892 assert.expect(2);
893 var attrs = {};
894 var models = [attrs];
895 new Backbone.Collection().add(models);
896 assert.equal(models.length, 1);
897 assert.ok(attrs === models[0]);
898 });
899
900 QUnit.test('#714: access `model.collection` in a brand new model.', function(assert) {
901 assert.expect(2);
902 var collection = new Backbone.Collection;
903 collection.url = '/test';
904 var Model = Backbone.Model.extend({
905 set: function(attrs) {
906 assert.equal(attrs.prop, 'value');
907 assert.equal(this.collection, collection);
908 return this;
909 }
910 });
911 collection.model = Model;
912 collection.create({prop: 'value'});
913 });
914
915 QUnit.test('#574, remove its own reference to the .models array.', function(assert) {
916 assert.expect(2);
917 var collection = new Backbone.Collection([
918 {id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}
919 ]);
920 assert.equal(collection.length, 6);
921 collection.remove(collection.models);
922 assert.equal(collection.length, 0);
923 });
924
925 QUnit.test('#861, adding models to a collection which do not pass validation, with validate:true', function(assert) {
926 assert.expect(2);
927 var Model = Backbone.Model.extend({
928 validate: function(attrs) {
929 if (attrs.id === 3) return "id can't be 3";
930 }
931 });
932
933 var Collection = Backbone.Collection.extend({
934 model: Model
935 });
936
937 var collection = new Collection;
938 collection.on('invalid', function() { assert.ok(true); });
939
940 collection.add([{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}], {validate: true});
941 assert.deepEqual(collection.pluck('id'), [1, 2, 4, 5, 6]);
942 });
943
944 QUnit.test('Invalid models are discarded with validate:true.', function(assert) {
945 assert.expect(5);
946 var collection = new Backbone.Collection;
947 collection.on('test', function() { assert.ok(true); });
948 collection.model = Backbone.Model.extend({
949 validate: function(attrs){ if (!attrs.valid) return 'invalid'; }
950 });
951 var model = new collection.model({id: 1, valid: true});
952 collection.add([model, {id: 2}], {validate: true});
953 model.trigger('test');
954 assert.ok(collection.get(model.cid));
955 assert.ok(collection.get(1));
956 assert.ok(!collection.get(2));
957 assert.equal(collection.length, 1);
958 });
959
960 QUnit.test('multiple copies of the same model', function(assert) {
961 assert.expect(3);
962 var collection = new Backbone.Collection();
963 var model = new Backbone.Model();
964 collection.add([model, model]);
965 assert.equal(collection.length, 1);
966 collection.add([{id: 1}, {id: 1}]);
967 assert.equal(collection.length, 2);
968 assert.equal(collection.last().id, 1);
969 });
970
971 QUnit.test('#964 - collection.get return inconsistent', function(assert) {
972 assert.expect(2);
973 var collection = new Backbone.Collection();
974 assert.ok(collection.get(null) === undefined);
975 assert.ok(collection.get() === undefined);
976 });
977
978 QUnit.test('#1112 - passing options.model sets collection.model', function(assert) {
979 assert.expect(2);
980 var Model = Backbone.Model.extend({});
981 var collection = new Backbone.Collection([{id: 1}], {model: Model});
982 assert.ok(collection.model === Model);
983 assert.ok(collection.at(0) instanceof Model);
984 });
985
986 QUnit.test('null and undefined are invalid ids.', function(assert) {
987 assert.expect(2);
988 var model = new Backbone.Model({id: 1});
989 var collection = new Backbone.Collection([model]);
990 model.set({id: null});
991 assert.ok(!collection.get('null'));
992 model.set({id: 1});
993 model.set({id: undefined});
994 assert.ok(!collection.get('undefined'));
995 });
996
997 QUnit.test('falsy comparator', function(assert) {
998 assert.expect(4);
999 var Col = Backbone.Collection.extend({
1000 comparator: function(model){ return model.id; }
1001 });
1002 var collection = new Col();
1003 var colFalse = new Col(null, {comparator: false});
1004 var colNull = new Col(null, {comparator: null});
1005 var colUndefined = new Col(null, {comparator: undefined});
1006 assert.ok(collection.comparator);
1007 assert.ok(!colFalse.comparator);
1008 assert.ok(!colNull.comparator);
1009 assert.ok(colUndefined.comparator);
1010 });
1011
1012 QUnit.test('#1355 - `options` is passed to success callbacks', function(assert) {
1013 assert.expect(2);
1014 var m = new Backbone.Model({x: 1});
1015 var collection = new Backbone.Collection();
1016 var opts = {
1017 opts: true,
1018 success: function(coll, resp, options) {
1019 assert.ok(options.opts);
1020 }
1021 };
1022 collection.sync = m.sync = function( method, coll, options ){
1023 options.success({});
1024 };
1025 collection.fetch(opts);
1026 collection.create(m, opts);
1027 });
1028
1029 QUnit.test("#1412 - Trigger 'request' and 'sync' events.", function(assert) {
1030 assert.expect(4);
1031 var collection = new Backbone.Collection;
1032 collection.url = '/test';
1033 Backbone.ajax = function(settings){ settings.success(); };
1034
1035 collection.on('request', function(obj, xhr, options) {
1036 assert.ok(obj === collection, "collection has correct 'request' event after fetching");
1037 });
1038 collection.on('sync', function(obj, response, options) {
1039 assert.ok(obj === collection, "collection has correct 'sync' event after fetching");
1040 });
1041 collection.fetch();
1042 collection.off();
1043
1044 collection.on('request', function(obj, xhr, options) {
1045 assert.ok(obj === collection.get(1), "collection has correct 'request' event after one of its models save");
1046 });
1047 collection.on('sync', function(obj, response, options) {
1048 assert.ok(obj === collection.get(1), "collection has correct 'sync' event after one of its models save");
1049 });
1050 collection.create({id: 1});
1051 collection.off();
1052 });
1053
1054 QUnit.test('#3283 - fetch, create calls success with context', function(assert) {
1055 assert.expect(2);
1056 var collection = new Backbone.Collection;
1057 collection.url = '/test';
1058 Backbone.ajax = function(settings) {
1059 settings.success.call(settings.context);
1060 };
1061 var obj = {};
1062 var options = {
1063 context: obj,
1064 success: function() {
1065 assert.equal(this, obj);
1066 }
1067 };
1068
1069 collection.fetch(options);
1070 collection.create({id: 1}, options);
1071 });
1072
1073 QUnit.test('#1447 - create with wait adds model.', function(assert) {
1074 assert.expect(1);
1075 var collection = new Backbone.Collection;
1076 var model = new Backbone.Model;
1077 model.sync = function(method, m, options){ options.success(); };
1078 collection.on('add', function(){ assert.ok(true); });
1079 collection.create(model, {wait: true});
1080 });
1081
1082 QUnit.test('#1448 - add sorts collection after merge.', function(assert) {
1083 assert.expect(1);
1084 var collection = new Backbone.Collection([
1085 {id: 1, x: 1},
1086 {id: 2, x: 2}
1087 ]);
1088 collection.comparator = function(model){ return model.get('x'); };
1089 collection.add({id: 1, x: 3}, {merge: true});
1090 assert.deepEqual(collection.pluck('id'), [2, 1]);
1091 });
1092
1093 QUnit.test('#1655 - groupBy can be used with a string argument.', function(assert) {
1094 assert.expect(3);
1095 var collection = new Backbone.Collection([{x: 1}, {x: 2}]);
1096 var grouped = collection.groupBy('x');
1097 assert.strictEqual(_.keys(grouped).length, 2);
1098 assert.strictEqual(grouped[1][0].get('x'), 1);
1099 assert.strictEqual(grouped[2][0].get('x'), 2);
1100 });
1101
1102 QUnit.test('#1655 - sortBy can be used with a string argument.', function(assert) {
1103 assert.expect(1);
1104 var collection = new Backbone.Collection([{x: 3}, {x: 1}, {x: 2}]);
1105 var values = _.map(collection.sortBy('x'), function(model) {
1106 return model.get('x');
1107 });
1108 assert.deepEqual(values, [1, 2, 3]);
1109 });
1110
1111 QUnit.test('#1604 - Removal during iteration.', function(assert) {
1112 assert.expect(0);
1113 var collection = new Backbone.Collection([{}, {}]);
1114 collection.on('add', function() {
1115 collection.at(0).destroy();
1116 });
1117 collection.add({}, {at: 0});
1118 });
1119
1120 QUnit.test('#1638 - `sort` during `add` triggers correctly.', function(assert) {
1121 var collection = new Backbone.Collection;
1122 collection.comparator = function(model) { return model.get('x'); };
1123 var added = [];
1124 collection.on('add', function(model) {
1125 model.set({x: 3});
1126 collection.sort();
1127 added.push(model.id);
1128 });
1129 collection.add([{id: 1, x: 1}, {id: 2, x: 2}]);
1130 assert.deepEqual(added, [1, 2]);
1131 });
1132
1133 QUnit.test('fetch parses models by default', function(assert) {
1134 assert.expect(1);
1135 var model = {};
1136 var Collection = Backbone.Collection.extend({
1137 url: 'test',
1138 model: Backbone.Model.extend({
1139 parse: function(resp) {
1140 assert.strictEqual(resp, model);
1141 }
1142 })
1143 });
1144 new Collection().fetch();
1145 this.ajaxSettings.success([model]);
1146 });
1147
1148 QUnit.test("`sort` shouldn't always fire on `add`", function(assert) {
1149 assert.expect(1);
1150 var collection = new Backbone.Collection([{id: 1}, {id: 2}, {id: 3}], {
1151 comparator: 'id'
1152 });
1153 collection.sort = function(){ assert.ok(true); };
1154 collection.add([]);
1155 collection.add({id: 1});
1156 collection.add([{id: 2}, {id: 3}]);
1157 collection.add({id: 4});
1158 });
1159
1160 QUnit.test('#1407 parse option on constructor parses collection and models', function(assert) {
1161 assert.expect(2);
1162 var model = {
1163 namespace: [{id: 1}, {id: 2}]
1164 };
1165 var Collection = Backbone.Collection.extend({
1166 model: Backbone.Model.extend({
1167 parse: function(m) {
1168 m.name = 'test';
1169 return m;
1170 }
1171 }),
1172 parse: function(m) {
1173 return m.namespace;
1174 }
1175 });
1176 var collection = new Collection(model, {parse: true});
1177
1178 assert.equal(collection.length, 2);
1179 assert.equal(collection.at(0).get('name'), 'test');
1180 });
1181
1182 QUnit.test('#1407 parse option on reset parses collection and models', function(assert) {
1183 assert.expect(2);
1184 var model = {
1185 namespace: [{id: 1}, {id: 2}]
1186 };
1187 var Collection = Backbone.Collection.extend({
1188 model: Backbone.Model.extend({
1189 parse: function(m) {
1190 m.name = 'test';
1191 return m;
1192 }
1193 }),
1194 parse: function(m) {
1195 return m.namespace;
1196 }
1197 });
1198 var collection = new Collection();
1199 collection.reset(model, {parse: true});
1200
1201 assert.equal(collection.length, 2);
1202 assert.equal(collection.at(0).get('name'), 'test');
1203 });
1204
1205
1206 QUnit.test('Reset includes previous models in triggered event.', function(assert) {
1207 assert.expect(1);
1208 var model = new Backbone.Model();
1209 var collection = new Backbone.Collection([model]);
1210 collection.on('reset', function(coll, options) {
1211 assert.deepEqual(options.previousModels, [model]);
1212 });
1213 collection.reset([]);
1214 });
1215
1216 QUnit.test('set', function(assert) {
1217 var m1 = new Backbone.Model();
1218 var m2 = new Backbone.Model({id: 2});
1219 var m3 = new Backbone.Model();
1220 var collection = new Backbone.Collection([m1, m2]);
1221
1222 // Test add/change/remove events
1223 collection.on('add', function(model) {
1224 assert.strictEqual(model, m3);
1225 });
1226 collection.on('change', function(model) {
1227 assert.strictEqual(model, m2);
1228 });
1229 collection.on('remove', function(model) {
1230 assert.strictEqual(model, m1);
1231 });
1232
1233 // remove: false doesn't remove any models
1234 collection.set([], {remove: false});
1235 assert.strictEqual(collection.length, 2);
1236
1237 // add: false doesn't add any models
1238 collection.set([m1, m2, m3], {add: false});
1239 assert.strictEqual(collection.length, 2);
1240
1241 // merge: false doesn't change any models
1242 collection.set([m1, {id: 2, a: 1}], {merge: false});
1243 assert.strictEqual(m2.get('a'), void 0);
1244
1245 // add: false, remove: false only merges existing models
1246 collection.set([m1, {id: 2, a: 0}, m3, {id: 4}], {add: false, remove: false});
1247 assert.strictEqual(collection.length, 2);
1248 assert.strictEqual(m2.get('a'), 0);
1249
1250 // default options add/remove/merge as appropriate
1251 collection.set([{id: 2, a: 1}, m3]);
1252 assert.strictEqual(collection.length, 2);
1253 assert.strictEqual(m2.get('a'), 1);
1254
1255 // Test removing models not passing an argument
1256 collection.off('remove').on('remove', function(model) {
1257 assert.ok(model === m2 || model === m3);
1258 });
1259 collection.set([]);
1260 assert.strictEqual(collection.length, 0);
1261
1262 // Test null models on set doesn't clear collection
1263 collection.off();
1264 collection.set([{id: 1}]);
1265 collection.set();
1266 assert.strictEqual(collection.length, 1);
1267 });
1268
1269 QUnit.test('set with only cids', function(assert) {
1270 assert.expect(3);
1271 var m1 = new Backbone.Model;
1272 var m2 = new Backbone.Model;
1273 var collection = new Backbone.Collection;
1274 collection.set([m1, m2]);
1275 assert.equal(collection.length, 2);
1276 collection.set([m1]);
1277 assert.equal(collection.length, 1);
1278 collection.set([m1, m1, m1, m2, m2], {remove: false});
1279 assert.equal(collection.length, 2);
1280 });
1281
1282 QUnit.test('set with only idAttribute', function(assert) {
1283 assert.expect(3);
1284 var m1 = {_id: 1};
1285 var m2 = {_id: 2};
1286 var Col = Backbone.Collection.extend({
1287 model: Backbone.Model.extend({
1288 idAttribute: '_id'
1289 })
1290 });
1291 var collection = new Col;
1292 collection.set([m1, m2]);
1293 assert.equal(collection.length, 2);
1294 collection.set([m1]);
1295 assert.equal(collection.length, 1);
1296 collection.set([m1, m1, m1, m2, m2], {remove: false});
1297 assert.equal(collection.length, 2);
1298 });
1299
1300 QUnit.test('set + merge with default values defined', function(assert) {
1301 var Model = Backbone.Model.extend({
1302 defaults: {
1303 key: 'value'
1304 }
1305 });
1306 var m = new Model({id: 1});
1307 var collection = new Backbone.Collection([m], {model: Model});
1308 assert.equal(collection.first().get('key'), 'value');
1309
1310 collection.set({id: 1, key: 'other'});
1311 assert.equal(collection.first().get('key'), 'other');
1312
1313 collection.set({id: 1, other: 'value'});
1314 assert.equal(collection.first().get('key'), 'other');
1315 assert.equal(collection.length, 1);
1316 });
1317
1318 QUnit.test('merge without mutation', function(assert) {
1319 var Model = Backbone.Model.extend({
1320 initialize: function(attrs, options) {
1321 if (attrs.child) {
1322 this.set('child', new Model(attrs.child, options), options);
1323 }
1324 }
1325 });
1326 var Collection = Backbone.Collection.extend({model: Model});
1327 var data = [{id: 1, child: {id: 2}}];
1328 var collection = new Collection(data);
1329 assert.equal(collection.first().id, 1);
1330 collection.set(data);
1331 assert.equal(collection.first().id, 1);
1332 collection.set([{id: 2, child: {id: 2}}].concat(data));
1333 assert.deepEqual(collection.pluck('id'), [2, 1]);
1334 });
1335
1336 QUnit.test('`set` and model level `parse`', function(assert) {
1337 var Model = Backbone.Model.extend({});
1338 var Collection = Backbone.Collection.extend({
1339 model: Model,
1340 parse: function(res) { return _.map(res.models, 'model'); }
1341 });
1342 var model = new Model({id: 1});
1343 var collection = new Collection(model);
1344 collection.set({models: [
1345 {model: {id: 1}},
1346 {model: {id: 2}}
1347 ]}, {parse: true});
1348 assert.equal(collection.first(), model);
1349 });
1350
1351 QUnit.test('`set` data is only parsed once', function(assert) {
1352 var collection = new Backbone.Collection();
1353 collection.model = Backbone.Model.extend({
1354 parse: function(data) {
1355 assert.equal(data.parsed, void 0);
1356 data.parsed = true;
1357 return data;
1358 }
1359 });
1360 collection.set({}, {parse: true});
1361 });
1362
1363 QUnit.test('`set` matches input order in the absence of a comparator', function(assert) {
1364 var one = new Backbone.Model({id: 1});
1365 var two = new Backbone.Model({id: 2});
1366 var three = new Backbone.Model({id: 3});
1367 var collection = new Backbone.Collection([one, two, three]);
1368 collection.set([{id: 3}, {id: 2}, {id: 1}]);
1369 assert.deepEqual(collection.models, [three, two, one]);
1370 collection.set([{id: 1}, {id: 2}]);
1371 assert.deepEqual(collection.models, [one, two]);
1372 collection.set([two, three, one]);
1373 assert.deepEqual(collection.models, [two, three, one]);
1374 collection.set([{id: 1}, {id: 2}], {remove: false});
1375 assert.deepEqual(collection.models, [two, three, one]);
1376 collection.set([{id: 1}, {id: 2}, {id: 3}], {merge: false});
1377 assert.deepEqual(collection.models, [one, two, three]);
1378 collection.set([three, two, one, {id: 4}], {add: false});
1379 assert.deepEqual(collection.models, [one, two, three]);
1380 });
1381
1382 QUnit.test('#1894 - Push should not trigger a sort', function(assert) {
1383 assert.expect(0);
1384 var Collection = Backbone.Collection.extend({
1385 comparator: 'id',
1386 sort: function() { assert.ok(false); }
1387 });
1388 new Collection().push({id: 1});
1389 });
1390
1391 QUnit.test('#2428 - push duplicate models, return the correct one', function(assert) {
1392 assert.expect(1);
1393 var collection = new Backbone.Collection;
1394 var model1 = collection.push({id: 101});
1395 var model2 = collection.push({id: 101});
1396 assert.ok(model2.cid === model1.cid);
1397 });
1398
1399 QUnit.test('`set` with non-normal id', function(assert) {
1400 var Collection = Backbone.Collection.extend({
1401 model: Backbone.Model.extend({idAttribute: '_id'})
1402 });
1403 var collection = new Collection({_id: 1});
1404 collection.set([{_id: 1, a: 1}], {add: false});
1405 assert.equal(collection.first().get('a'), 1);
1406 });
1407
1408 QUnit.test('#1894 - `sort` can optionally be turned off', function(assert) {
1409 assert.expect(0);
1410 var Collection = Backbone.Collection.extend({
1411 comparator: 'id',
1412 sort: function() { assert.ok(false); }
1413 });
1414 new Collection().add({id: 1}, {sort: false});
1415 });
1416
1417 QUnit.test('#1915 - `parse` data in the right order in `set`', function(assert) {
1418 var collection = new (Backbone.Collection.extend({
1419 parse: function(data) {
1420 assert.strictEqual(data.status, 'ok');
1421 return data.data;
1422 }
1423 }));
1424 var res = {status: 'ok', data: [{id: 1}]};
1425 collection.set(res, {parse: true});
1426 });
1427
1428 QUnit.test('#1939 - `parse` is passed `options`', function(assert) {
1429 var done = assert.async();
1430 assert.expect(1);
1431 var collection = new (Backbone.Collection.extend({
1432 url: '/',
1433 parse: function(data, options) {
1434 assert.strictEqual(options.xhr.someHeader, 'headerValue');
1435 return data;
1436 }
1437 }));
1438 var ajax = Backbone.ajax;
1439 Backbone.ajax = function(params) {
1440 _.defer(params.success, []);
1441 return {someHeader: 'headerValue'};
1442 };
1443 collection.fetch({
1444 success: function() { done(); }
1445 });
1446 Backbone.ajax = ajax;
1447 });
1448
1449 QUnit.test('fetch will pass extra options to success callback', function(assert) {
1450 assert.expect(1);
1451 var SpecialSyncCollection = Backbone.Collection.extend({
1452 url: '/test',
1453 sync: function(method, collection, options) {
1454 _.extend(options, {specialSync: true});
1455 return Backbone.Collection.prototype.sync.call(this, method, collection, options);
1456 }
1457 });
1458
1459 var collection = new SpecialSyncCollection();
1460
1461 var onSuccess = function(coll, resp, options) {
1462 assert.ok(options.specialSync, 'Options were passed correctly to callback');
1463 };
1464
1465 collection.fetch({success: onSuccess});
1466 this.ajaxSettings.success();
1467 });
1468
1469 QUnit.test('`add` only `sort`s when necessary', function(assert) {
1470 assert.expect(2);
1471 var collection = new (Backbone.Collection.extend({
1472 comparator: 'a'
1473 }))([{id: 1}, {id: 2}, {id: 3}]);
1474 collection.on('sort', function() { assert.ok(true); });
1475 collection.add({id: 4}); // do sort, new model
1476 collection.add({id: 1, a: 1}, {merge: true}); // do sort, comparator change
1477 collection.add({id: 1, b: 1}, {merge: true}); // don't sort, no comparator change
1478 collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no comparator change
1479 collection.add(collection.models); // don't sort, nothing new
1480 collection.add(collection.models, {merge: true}); // don't sort
1481 });
1482
1483 QUnit.test('`add` only `sort`s when necessary with comparator function', function(assert) {
1484 assert.expect(3);
1485 var collection = new (Backbone.Collection.extend({
1486 comparator: function(m1, m2) {
1487 return m1.get('a') > m2.get('a') ? 1 : m1.get('a') < m2.get('a') ? -1 : 0;
1488 }
1489 }))([{id: 1}, {id: 2}, {id: 3}]);
1490 collection.on('sort', function() { assert.ok(true); });
1491 collection.add({id: 4}); // do sort, new model
1492 collection.add({id: 1, a: 1}, {merge: true}); // do sort, model change
1493 collection.add({id: 1, b: 1}, {merge: true}); // do sort, model change
1494 collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no model change
1495 collection.add(collection.models); // don't sort, nothing new
1496 collection.add(collection.models, {merge: true}); // don't sort
1497 });
1498
1499 QUnit.test('Attach options to collection.', function(assert) {
1500 assert.expect(2);
1501 var Model = Backbone.Model;
1502 var comparator = function(){};
1503
1504 var collection = new Backbone.Collection([], {
1505 model: Model,
1506 comparator: comparator
1507 });
1508
1509 assert.ok(collection.model === Model);
1510 assert.ok(collection.comparator === comparator);
1511 });
1512
1513 QUnit.test('Pass falsey for `models` for empty Col with `options`', function(assert) {
1514 assert.expect(9);
1515 var opts = {a: 1, b: 2};
1516 _.forEach([undefined, null, false], function(falsey) {
1517 var Collection = Backbone.Collection.extend({
1518 initialize: function(models, options) {
1519 assert.strictEqual(models, falsey);
1520 assert.strictEqual(options, opts);
1521 }
1522 });
1523
1524 var collection = new Collection(falsey, opts);
1525 assert.strictEqual(collection.length, 0);
1526 });
1527 });
1528
1529 QUnit.test('`add` overrides `set` flags', function(assert) {
1530 var collection = new Backbone.Collection();
1531 collection.once('add', function(model, coll, options) {
1532 coll.add({id: 2}, options);
1533 });
1534 collection.set({id: 1});
1535 assert.equal(collection.length, 2);
1536 });
1537
1538 QUnit.test('#2606 - Collection#create, success arguments', function(assert) {
1539 assert.expect(1);
1540 var collection = new Backbone.Collection;
1541 collection.url = 'test';
1542 collection.create({}, {
1543 success: function(model, resp, options) {
1544 assert.strictEqual(resp, 'response');
1545 }
1546 });
1547 this.ajaxSettings.success('response');
1548 });
1549
1550 QUnit.test('#2612 - nested `parse` works with `Collection#set`', function(assert) {
1551
1552 var Job = Backbone.Model.extend({
1553 constructor: function() {
1554 this.items = new Items();
1555 Backbone.Model.apply(this, arguments);
1556 },
1557 parse: function(attrs) {
1558 this.items.set(attrs.items, {parse: true});
1559 return _.omit(attrs, 'items');
1560 }
1561 });
1562
1563 var Item = Backbone.Model.extend({
1564 constructor: function() {
1565 this.subItems = new Backbone.Collection();
1566 Backbone.Model.apply(this, arguments);
1567 },
1568 parse: function(attrs) {
1569 this.subItems.set(attrs.subItems, {parse: true});
1570 return _.omit(attrs, 'subItems');
1571 }
1572 });
1573
1574 var Items = Backbone.Collection.extend({
1575 model: Item
1576 });
1577
1578 var data = {
1579 name: 'JobName',
1580 id: 1,
1581 items: [{
1582 id: 1,
1583 name: 'Sub1',
1584 subItems: [
1585 {id: 1, subName: 'One'},
1586 {id: 2, subName: 'Two'}
1587 ]
1588 }, {
1589 id: 2,
1590 name: 'Sub2',
1591 subItems: [
1592 {id: 3, subName: 'Three'},
1593 {id: 4, subName: 'Four'}
1594 ]
1595 }]
1596 };
1597
1598 var newData = {
1599 name: 'NewJobName',
1600 id: 1,
1601 items: [{
1602 id: 1,
1603 name: 'NewSub1',
1604 subItems: [
1605 {id: 1, subName: 'NewOne'},
1606 {id: 2, subName: 'NewTwo'}
1607 ]
1608 }, {
1609 id: 2,
1610 name: 'NewSub2',
1611 subItems: [
1612 {id: 3, subName: 'NewThree'},
1613 {id: 4, subName: 'NewFour'}
1614 ]
1615 }]
1616 };
1617
1618 var job = new Job(data, {parse: true});
1619 assert.equal(job.get('name'), 'JobName');
1620 assert.equal(job.items.at(0).get('name'), 'Sub1');
1621 assert.equal(job.items.length, 2);
1622 assert.equal(job.items.get(1).subItems.get(1).get('subName'), 'One');
1623 assert.equal(job.items.get(2).subItems.get(3).get('subName'), 'Three');
1624 job.set(job.parse(newData, {parse: true}));
1625 assert.equal(job.get('name'), 'NewJobName');
1626 assert.equal(job.items.at(0).get('name'), 'NewSub1');
1627 assert.equal(job.items.length, 2);
1628 assert.equal(job.items.get(1).subItems.get(1).get('subName'), 'NewOne');
1629 assert.equal(job.items.get(2).subItems.get(3).get('subName'), 'NewThree');
1630 });
1631
1632 QUnit.test('_addReference binds all collection events & adds to the lookup hashes', function(assert) {
1633 assert.expect(8);
1634
1635 var calls = {add: 0, remove: 0};
1636
1637 var Collection = Backbone.Collection.extend({
1638
1639 _addReference: function(model) {
1640 Backbone.Collection.prototype._addReference.apply(this, arguments);
1641 calls.add++;
1642 assert.equal(model, this._byId[model.id]);
1643 assert.equal(model, this._byId[model.cid]);
1644 assert.equal(model._events.all.length, 1);
1645 },
1646
1647 _removeReference: function(model) {
1648 Backbone.Collection.prototype._removeReference.apply(this, arguments);
1649 calls.remove++;
1650 assert.equal(this._byId[model.id], void 0);
1651 assert.equal(this._byId[model.cid], void 0);
1652 assert.equal(model.collection, void 0);
1653 }
1654
1655 });
1656
1657 var collection = new Collection();
1658 var model = collection.add({id: 1});
1659 collection.remove(model);
1660
1661 assert.equal(calls.add, 1);
1662 assert.equal(calls.remove, 1);
1663 });
1664
1665 QUnit.test('Do not allow duplicate models to be `add`ed or `set`', function(assert) {
1666 var collection = new Backbone.Collection();
1667
1668 collection.add([{id: 1}, {id: 1}]);
1669 assert.equal(collection.length, 1);
1670 assert.equal(collection.models.length, 1);
1671
1672 collection.set([{id: 1}, {id: 1}]);
1673 assert.equal(collection.length, 1);
1674 assert.equal(collection.models.length, 1);
1675 });
1676
1677 QUnit.test('#3020: #set with {add: false} should not throw.', function(assert) {
1678 assert.expect(2);
1679 var collection = new Backbone.Collection;
1680 collection.set([{id: 1}], {add: false});
1681 assert.strictEqual(collection.length, 0);
1682 assert.strictEqual(collection.models.length, 0);
1683 });
1684
1685 QUnit.test('create with wait, model instance, #3028', function(assert) {
1686 assert.expect(1);
1687 var collection = new Backbone.Collection();
1688 var model = new Backbone.Model({id: 1});
1689 model.sync = function(){
1690 assert.equal(this.collection, collection);
1691 };
1692 collection.create(model, {wait: true});
1693 });
1694
1695 QUnit.test('modelId', function(assert) {
1696 var Stooge = Backbone.Model.extend();
1697 var StoogeCollection = Backbone.Collection.extend();
1698
1699 // Default to using `id` if `model::idAttribute` and `Collection::model::idAttribute` not present.
1700 assert.equal(StoogeCollection.prototype.modelId({id: 1}), 1);
1701
1702 // Default to using `model::idAttribute` if present.
1703 Stooge.prototype.idAttribute = '_id';
1704 var model = new Stooge({_id: 1});
1705 assert.equal(StoogeCollection.prototype.modelId(model.attributes, model.idAttribute), 1);
1706
1707 // Default to using `Collection::model::idAttribute` if model::idAttribute not present.
1708 StoogeCollection.prototype.model = Stooge;
1709 assert.equal(StoogeCollection.prototype.modelId({_id: 1}), 1);
1710
1711 });
1712
1713 QUnit.test('Polymorphic models work with "simple" constructors', function(assert) {
1714 var A = Backbone.Model.extend();
1715 var B = Backbone.Model.extend();
1716 var C = Backbone.Collection.extend({
1717 model: function(attrs) {
1718 return attrs.type === 'a' ? new A(attrs) : new B(attrs);
1719 }
1720 });
1721 var collection = new C([{id: 1, type: 'a'}, {id: 2, type: 'b'}]);
1722 assert.equal(collection.length, 2);
1723 assert.ok(collection.at(0) instanceof A);
1724 assert.equal(collection.at(0).id, 1);
1725 assert.ok(collection.at(1) instanceof B);
1726 assert.equal(collection.at(1).id, 2);
1727 });
1728
1729 QUnit.test('Polymorphic models work with "advanced" constructors', function(assert) {
1730 var A = Backbone.Model.extend({idAttribute: '_id'});
1731 var B = Backbone.Model.extend({idAttribute: '_id'});
1732 var C = Backbone.Collection.extend({
1733 model: Backbone.Model.extend({
1734 constructor: function(attrs) {
1735 return attrs.type === 'a' ? new A(attrs) : new B(attrs);
1736 },
1737
1738 idAttribute: '_id'
1739 })
1740 });
1741 var collection = new C([{_id: 1, type: 'a'}, {_id: 2, type: 'b'}]);
1742 assert.equal(collection.length, 2);
1743 assert.ok(collection.at(0) instanceof A);
1744 assert.equal(collection.at(0), collection.get(1));
1745 assert.ok(collection.at(1) instanceof B);
1746 assert.equal(collection.at(1), collection.get(2));
1747
1748 C = Backbone.Collection.extend({
1749 model: function(attrs) {
1750 return attrs.type === 'a' ? new A(attrs) : new B(attrs);
1751 },
1752
1753 modelId: function(attrs) {
1754 return attrs.type + '-' + attrs.id;
1755 }
1756 });
1757 collection = new C([{id: 1, type: 'a'}, {id: 1, type: 'b'}]);
1758 assert.equal(collection.length, 2);
1759 assert.ok(collection.at(0) instanceof A);
1760 assert.equal(collection.at(0), collection.get('a-1'));
1761 assert.ok(collection.at(1) instanceof B);
1762 assert.equal(collection.at(1), collection.get('b-1'));
1763 });
1764
1765 QUnit.test('Collection with polymorphic models receives id from modelId using model instance idAttribute', function(assert) {
1766 assert.expect(6);
1767 // When the polymorphic models use 'id' for the idAttribute, all is fine.
1768 var C1 = Backbone.Collection.extend({
1769 model: function(attrs) {
1770 return new Backbone.Model(attrs);
1771 }
1772 });
1773 var c1 = new C1({id: 1});
1774 assert.equal(c1.get(1).id, 1);
1775 assert.equal(c1.modelId({id: 1}), 1);
1776
1777 // If the polymorphic models define their own idAttribute,
1778 // the modelId method will use the model's idAttribute property before the
1779 // collection's model constructor's.
1780 var M = Backbone.Model.extend({
1781 idAttribute: '_id'
1782 });
1783 var C2 = Backbone.Collection.extend({
1784 model: function(attrs) {
1785 return new M(attrs);
1786 }
1787 });
1788 var c2 = new C2({_id: 1});
1789 assert.equal(c2.get(1), c2.at(0));
1790 assert.equal(c2.modelId(c2.at(0).attributes, c2.at(0).idAttribute), 1);
1791 var m = new M({_id: 2});
1792 c2.add(m);
1793 assert.equal(c2.get(2), m);
1794 assert.equal(c2.modelId(m.attributes, m.idAttribute), 2);
1795 });
1796
1797 QUnit.test('Collection implements Iterable, values is default iterator function', function(assert) {
1798 /* global Symbol */
1799 var $$iterator = typeof Symbol === 'function' && Symbol.iterator;
1800 // This test only applies to environments which define Symbol.iterator.
1801 if (!$$iterator) {
1802 assert.expect(0);
1803 return;
1804 }
1805 assert.expect(2);
1806 var collection = new Backbone.Collection([]);
1807 assert.strictEqual(collection[$$iterator], collection.values);
1808 var iterator = collection[$$iterator]();
1809 assert.deepEqual(iterator.next(), {value: void 0, done: true});
1810 });
1811
1812 QUnit.test('Collection.values iterates models in sorted order', function(assert) {
1813 assert.expect(4);
1814 var one = new Backbone.Model({id: 1});
1815 var two = new Backbone.Model({id: 2});
1816 var three = new Backbone.Model({id: 3});
1817 var collection = new Backbone.Collection([one, two, three]);
1818 var iterator = collection.values();
1819 assert.strictEqual(iterator.next().value, one);
1820 assert.strictEqual(iterator.next().value, two);
1821 assert.strictEqual(iterator.next().value, three);
1822 assert.strictEqual(iterator.next().value, void 0);
1823 });
1824
1825 QUnit.test('Collection.keys iterates ids in sorted order', function(assert) {
1826 assert.expect(4);
1827 var one = new Backbone.Model({id: 1});
1828 var two = new Backbone.Model({id: 2});
1829 var three = new Backbone.Model({id: 3});
1830 var collection = new Backbone.Collection([one, two, three]);
1831 var iterator = collection.keys();
1832 assert.strictEqual(iterator.next().value, 1);
1833 assert.strictEqual(iterator.next().value, 2);
1834 assert.strictEqual(iterator.next().value, 3);
1835 assert.strictEqual(iterator.next().value, void 0);
1836 });
1837
1838 QUnit.test('Collection.entries iterates ids and models in sorted order', function(assert) {
1839 assert.expect(4);
1840 var one = new Backbone.Model({id: 1});
1841 var two = new Backbone.Model({id: 2});
1842 var three = new Backbone.Model({id: 3});
1843 var collection = new Backbone.Collection([one, two, three]);
1844 var iterator = collection.entries();
1845 assert.deepEqual(iterator.next().value, [1, one]);
1846 assert.deepEqual(iterator.next().value, [2, two]);
1847 assert.deepEqual(iterator.next().value, [3, three]);
1848 assert.strictEqual(iterator.next().value, void 0);
1849 });
1850
1851 QUnit.test('#3039 #3951: adding at index fires with correct at', function(assert) {
1852 assert.expect(4);
1853 var collection = new Backbone.Collection([{val: 0}, {val: 4}]);
1854 collection.on('add', function(model, coll, options) {
1855 assert.equal(model.get('val'), options.index);
1856 });
1857 collection.add([{val: 1}, {val: 2}, {val: 3}], {at: 1});
1858 collection.add({val: 5}, {at: 10});
1859 });
1860
1861 QUnit.test('#3039: index is not sent when at is not specified', function(assert) {
1862 assert.expect(2);
1863 var collection = new Backbone.Collection([{at: 0}]);
1864 collection.on('add', function(model, coll, options) {
1865 assert.equal(undefined, options.index);
1866 });
1867 collection.add([{at: 1}, {at: 2}]);
1868 });
1869
1870 QUnit.test('#3199 - Order changing should trigger a sort', function(assert) {
1871 assert.expect(1);
1872 var one = new Backbone.Model({id: 1});
1873 var two = new Backbone.Model({id: 2});
1874 var three = new Backbone.Model({id: 3});
1875 var collection = new Backbone.Collection([one, two, three]);
1876 collection.on('sort', function() {
1877 assert.ok(true);
1878 });
1879 collection.set([{id: 3}, {id: 2}, {id: 1}]);
1880 });
1881
1882 QUnit.test('#3199 - Adding a model should trigger a sort', function(assert) {
1883 assert.expect(1);
1884 var one = new Backbone.Model({id: 1});
1885 var two = new Backbone.Model({id: 2});
1886 var three = new Backbone.Model({id: 3});
1887 var collection = new Backbone.Collection([one, two, three]);
1888 collection.on('sort', function() {
1889 assert.ok(true);
1890 });
1891 collection.set([{id: 1}, {id: 2}, {id: 3}, {id: 0}]);
1892 });
1893
1894 QUnit.test('#3199 - Order not changing should not trigger a sort', function(assert) {
1895 assert.expect(0);
1896 var one = new Backbone.Model({id: 1});
1897 var two = new Backbone.Model({id: 2});
1898 var three = new Backbone.Model({id: 3});
1899 var collection = new Backbone.Collection([one, two, three]);
1900 collection.on('sort', function() {
1901 assert.ok(false);
1902 });
1903 collection.set([{id: 1}, {id: 2}, {id: 3}]);
1904 });
1905
1906 QUnit.test('add supports negative indexes', function(assert) {
1907 assert.expect(1);
1908 var collection = new Backbone.Collection([{id: 1}]);
1909 collection.add([{id: 2}, {id: 3}], {at: -1});
1910 collection.add([{id: 2.5}], {at: -2});
1911 collection.add([{id: 0.5}], {at: -6});
1912 assert.equal(collection.pluck('id').join(','), '0.5,1,2,2.5,3');
1913 });
1914
1915 QUnit.test('#set accepts options.at as a string', function(assert) {
1916 assert.expect(1);
1917 var collection = new Backbone.Collection([{id: 1}, {id: 2}]);
1918 collection.add([{id: 3}], {at: '1'});
1919 assert.deepEqual(collection.pluck('id'), [1, 3, 2]);
1920 });
1921
1922 QUnit.test('adding multiple models triggers `update` event once', function(assert) {
1923 assert.expect(1);
1924 var collection = new Backbone.Collection;
1925 collection.on('update', function() { assert.ok(true); });
1926 collection.add([{id: 1}, {id: 2}, {id: 3}]);
1927 });
1928
1929 QUnit.test('removing models triggers `update` event once', function(assert) {
1930 assert.expect(1);
1931 var collection = new Backbone.Collection([{id: 1}, {id: 2}, {id: 3}]);
1932 collection.on('update', function() { assert.ok(true); });
1933 collection.remove([{id: 1}, {id: 2}]);
1934 });
1935
1936 QUnit.test('remove does not trigger `update` when nothing removed', function(assert) {
1937 assert.expect(0);
1938 var collection = new Backbone.Collection([{id: 1}, {id: 2}]);
1939 collection.on('update', function() { assert.ok(false); });
1940 collection.remove([{id: 3}]);
1941 });
1942
1943 QUnit.test('set triggers `set` event once', function(assert) {
1944 assert.expect(1);
1945 var collection = new Backbone.Collection([{id: 1}, {id: 2}]);
1946 collection.on('update', function() { assert.ok(true); });
1947 collection.set([{id: 1}, {id: 3}]);
1948 });
1949
1950 QUnit.test('set does not trigger `update` event when nothing added nor removed', function(assert) {
1951 var collection = new Backbone.Collection([{id: 1}, {id: 2}]);
1952 collection.on('update', function(coll, options) {
1953 assert.equal(options.changes.added.length, 0);
1954 assert.equal(options.changes.removed.length, 0);
1955 assert.equal(options.changes.merged.length, 2);
1956 });
1957 collection.set([{id: 1}, {id: 2}]);
1958 });
1959
1960 QUnit.test('#3610 - invoke collects arguments', function(assert) {
1961 assert.expect(3);
1962 var Model = Backbone.Model.extend({
1963 method: function(x, y, z) {
1964 assert.equal(x, 1);
1965 assert.equal(y, 2);
1966 assert.equal(z, 3);
1967 }
1968 });
1969 var Collection = Backbone.Collection.extend({
1970 model: Model
1971 });
1972 var collection = new Collection([{id: 1}]);
1973 collection.invoke('method', 1, 2, 3);
1974 });
1975
1976 QUnit.test('#3662 - triggering change without model will not error', function(assert) {
1977 assert.expect(1);
1978 var collection = new Backbone.Collection([{id: 1}]);
1979 var model = collection.first();
1980 collection.on('change', function(m) {
1981 assert.equal(m, undefined);
1982 });
1983 model.trigger('change');
1984 });
1985
1986 QUnit.test('#3871 - falsy parse result creates empty collection', function(assert) {
1987 var collection = new (Backbone.Collection.extend({
1988 parse: function(data, options) {}
1989 }));
1990 collection.set('', {parse: true});
1991 assert.equal(collection.length, 0);
1992 });
1993
1994 QUnit.test("#3711 - remove's `update` event returns one removed model", function(assert) {
1995 var model = new Backbone.Model({id: 1, title: 'First Post'});
1996 var collection = new Backbone.Collection([model]);
1997 collection.on('update', function(context, options) {
1998 var changed = options.changes;
1999 assert.deepEqual(changed.added, []);
2000 assert.deepEqual(changed.merged, []);
2001 assert.strictEqual(changed.removed[0], model);
2002 });
2003 collection.remove(model);
2004 });
2005
2006 QUnit.test("#3711 - remove's `update` event returns multiple removed models", function(assert) {
2007 var model = new Backbone.Model({id: 1, title: 'First Post'});
2008 var model2 = new Backbone.Model({id: 2, title: 'Second Post'});
2009 var collection = new Backbone.Collection([model, model2]);
2010 collection.on('update', function(context, options) {
2011 var changed = options.changes;
2012 assert.deepEqual(changed.added, []);
2013 assert.deepEqual(changed.merged, []);
2014 assert.ok(changed.removed.length === 2);
2015
2016 assert.ok(_.indexOf(changed.removed, model) > -1 && _.indexOf(changed.removed, model2) > -1);
2017 });
2018 collection.remove([model, model2]);
2019 });
2020
2021 QUnit.test("#3711 - set's `update` event returns one added model", function(assert) {
2022 var model = new Backbone.Model({id: 1, title: 'First Post'});
2023 var collection = new Backbone.Collection();
2024 collection.on('update', function(context, options) {
2025 var addedModels = options.changes.added;
2026 assert.ok(addedModels.length === 1);
2027 assert.strictEqual(addedModels[0], model);
2028 });
2029 collection.set(model);
2030 });
2031
2032 QUnit.test("#3711 - set's `update` event returns multiple added models", function(assert) {
2033 var model = new Backbone.Model({id: 1, title: 'First Post'});
2034 var model2 = new Backbone.Model({id: 2, title: 'Second Post'});
2035 var collection = new Backbone.Collection();
2036 collection.on('update', function(context, options) {
2037 var addedModels = options.changes.added;
2038 assert.ok(addedModels.length === 2);
2039 assert.strictEqual(addedModels[0], model);
2040 assert.strictEqual(addedModels[1], model2);
2041 });
2042 collection.set([model, model2]);
2043 });
2044
2045 QUnit.test("#3711 - set's `update` event returns one removed model", function(assert) {
2046 var model = new Backbone.Model({id: 1, title: 'First Post'});
2047 var model2 = new Backbone.Model({id: 2, title: 'Second Post'});
2048 var model3 = new Backbone.Model({id: 3, title: 'My Last Post'});
2049 var collection = new Backbone.Collection([model]);
2050 collection.on('update', function(context, options) {
2051 var changed = options.changes;
2052 assert.equal(changed.added.length, 2);
2053 assert.equal(changed.merged.length, 0);
2054 assert.ok(changed.removed.length === 1);
2055 assert.strictEqual(changed.removed[0], model);
2056 });
2057 collection.set([model2, model3]);
2058 });
2059
2060 QUnit.test("#3711 - set's `update` event returns multiple removed models", function(assert) {
2061 var model = new Backbone.Model({id: 1, title: 'First Post'});
2062 var model2 = new Backbone.Model({id: 2, title: 'Second Post'});
2063 var model3 = new Backbone.Model({id: 3, title: 'My Last Post'});
2064 var collection = new Backbone.Collection([model, model2]);
2065 collection.on('update', function(context, options) {
2066 var removedModels = options.changes.removed;
2067 assert.ok(removedModels.length === 2);
2068 assert.strictEqual(removedModels[0], model);
2069 assert.strictEqual(removedModels[1], model2);
2070 });
2071 collection.set([model3]);
2072 });
2073
2074 QUnit.test("#3711 - set's `update` event returns one merged model", function(assert) {
2075 var model = new Backbone.Model({id: 1, title: 'First Post'});
2076 var model2 = new Backbone.Model({id: 2, title: 'Second Post'});
2077 var model2Update = new Backbone.Model({id: 2, title: 'Second Post V2'});
2078 var collection = new Backbone.Collection([model, model2]);
2079 collection.on('update', function(context, options) {
2080 var mergedModels = options.changes.merged;
2081 assert.ok(mergedModels.length === 1);
2082 assert.strictEqual(mergedModels[0].get('title'), model2Update.get('title'));
2083 });
2084 collection.set([model2Update]);
2085 });
2086
2087 QUnit.test("#3711 - set's `update` event returns multiple merged models", function(assert) {
2088 var model = new Backbone.Model({id: 1, title: 'First Post'});
2089 var modelUpdate = new Backbone.Model({id: 1, title: 'First Post V2'});
2090 var model2 = new Backbone.Model({id: 2, title: 'Second Post'});
2091 var model2Update = new Backbone.Model({id: 2, title: 'Second Post V2'});
2092 var collection = new Backbone.Collection([model, model2]);
2093 collection.on('update', function(context, options) {
2094 var mergedModels = options.changes.merged;
2095 assert.ok(mergedModels.length === 2);
2096 assert.strictEqual(mergedModels[0].get('title'), model2Update.get('title'));
2097 assert.strictEqual(mergedModels[1].get('title'), modelUpdate.get('title'));
2098 });
2099 collection.set([model2Update, modelUpdate]);
2100 });
2101
2102 QUnit.test("#3711 - set's `update` event should not be triggered adding a model which already exists exactly alike", function(assert) {
2103 var fired = false;
2104 var model = new Backbone.Model({id: 1, title: 'First Post'});
2105 var collection = new Backbone.Collection([model]);
2106 collection.on('update', function(context, options) {
2107 fired = true;
2108 });
2109 collection.set([model]);
2110 assert.equal(fired, false);
2111 });
2112
2113 QUnit.test('get models with `attributes` key', function(assert) {
2114 var model = {id: 1, attributes: {}};
2115 var collection = new Backbone.Collection([model]);
2116 assert.ok(collection.get(model));
2117 });
2118
2119 QUnit.test('#4233 - can instantiate new model in ES class Collection', function(assert) {
2120 var model;
2121 try {
2122 model = new Function('return ({\n' +
2123 ' model(attrs, options) {\n' +
2124 ' var MyModel = Backbone.Model.extend({});\n' +
2125 ' return new MyModel(attrs, options);\n' +
2126 ' }\n' +
2127 '}).model')();
2128 } catch (error) {
2129 model = error;
2130 }
2131
2132 if (model instanceof SyntaxError) {
2133 assert.expect(0);
2134 return;
2135 }
2136
2137 assert.expect(1);
2138
2139 var MyCollection = Backbone.Collection.extend({
2140 modelId: function(attr) {
2141 return attr.x;
2142 },
2143
2144 model: model
2145 });
2146
2147 var instance = new MyCollection([{a: 2}]);
2148
2149 assert.ok(instance, 'Should instantiate collection with model');
2150 });
2151 })(QUnit);