PageRenderTime 58ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/test/collection.js

http://github.com/documentcloud/backbone
JavaScript | 2112 lines | 1877 code | 217 blank | 18 comment | 17 complexity | 52c72f67bf221b2c21a969f7509232f9 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. (function(QUnit) {
  2. var a, b, c, d, e, col, otherCol;
  3. QUnit.module('Backbone.Collection', {
  4. beforeEach: function(assert) {
  5. a = new Backbone.Model({id: 3, label: 'a'});
  6. b = new Backbone.Model({id: 2, label: 'b'});
  7. c = new Backbone.Model({id: 1, label: 'c'});
  8. d = new Backbone.Model({id: 0, label: 'd'});
  9. e = null;
  10. col = new Backbone.Collection([a, b, c, d]);
  11. otherCol = new Backbone.Collection();
  12. }
  13. });
  14. QUnit.test('new and sort', function(assert) {
  15. assert.expect(6);
  16. var counter = 0;
  17. col.on('sort', function(){ counter++; });
  18. assert.deepEqual(col.pluck('label'), ['a', 'b', 'c', 'd']);
  19. col.comparator = function(m1, m2) {
  20. return m1.id > m2.id ? -1 : 1;
  21. };
  22. col.sort();
  23. assert.equal(counter, 1);
  24. assert.deepEqual(col.pluck('label'), ['a', 'b', 'c', 'd']);
  25. col.comparator = function(model) { return model.id; };
  26. col.sort();
  27. assert.equal(counter, 2);
  28. assert.deepEqual(col.pluck('label'), ['d', 'c', 'b', 'a']);
  29. assert.equal(col.length, 4);
  30. });
  31. QUnit.test('String comparator.', function(assert) {
  32. assert.expect(1);
  33. var collection = new Backbone.Collection([
  34. {id: 3},
  35. {id: 1},
  36. {id: 2}
  37. ], {comparator: 'id'});
  38. assert.deepEqual(collection.pluck('id'), [1, 2, 3]);
  39. });
  40. QUnit.test('new and parse', function(assert) {
  41. assert.expect(3);
  42. var Collection = Backbone.Collection.extend({
  43. parse: function(data) {
  44. return _.filter(data, function(datum) {
  45. return datum.a % 2 === 0;
  46. });
  47. }
  48. });
  49. var models = [{a: 1}, {a: 2}, {a: 3}, {a: 4}];
  50. var collection = new Collection(models, {parse: true});
  51. assert.strictEqual(collection.length, 2);
  52. assert.strictEqual(collection.first().get('a'), 2);
  53. assert.strictEqual(collection.last().get('a'), 4);
  54. });
  55. QUnit.test('clone preserves model and comparator', function(assert) {
  56. assert.expect(3);
  57. var Model = Backbone.Model.extend();
  58. var comparator = function(model){ return model.id; };
  59. var collection = new Backbone.Collection([{id: 1}], {
  60. model: Model,
  61. comparator: comparator
  62. }).clone();
  63. collection.add({id: 2});
  64. assert.ok(collection.at(0) instanceof Model);
  65. assert.ok(collection.at(1) instanceof Model);
  66. assert.strictEqual(collection.comparator, comparator);
  67. });
  68. QUnit.test('get', function(assert) {
  69. assert.expect(6);
  70. assert.equal(col.get(0), d);
  71. assert.equal(col.get(d.clone()), d);
  72. assert.equal(col.get(2), b);
  73. assert.equal(col.get({id: 1}), c);
  74. assert.equal(col.get(c.clone()), c);
  75. assert.equal(col.get(col.first().cid), col.first());
  76. });
  77. QUnit.test('get with non-default ids', function(assert) {
  78. assert.expect(5);
  79. var MongoModel = Backbone.Model.extend({idAttribute: '_id'});
  80. var model = new MongoModel({_id: 100});
  81. var collection = new Backbone.Collection([model], {model: MongoModel});
  82. assert.equal(collection.get(100), model);
  83. assert.equal(collection.get(model.cid), model);
  84. assert.equal(collection.get(model), model);
  85. assert.equal(collection.get(101), void 0);
  86. var collection2 = new Backbone.Collection();
  87. collection2.model = MongoModel;
  88. collection2.add(model.attributes);
  89. assert.equal(collection2.get(model.clone()), collection2.first());
  90. });
  91. QUnit.test('has', function(assert) {
  92. assert.expect(15);
  93. assert.ok(col.has(a));
  94. assert.ok(col.has(b));
  95. assert.ok(col.has(c));
  96. assert.ok(col.has(d));
  97. assert.ok(col.has(a.id));
  98. assert.ok(col.has(b.id));
  99. assert.ok(col.has(c.id));
  100. assert.ok(col.has(d.id));
  101. assert.ok(col.has(a.cid));
  102. assert.ok(col.has(b.cid));
  103. assert.ok(col.has(c.cid));
  104. assert.ok(col.has(d.cid));
  105. var outsider = new Backbone.Model({id: 4});
  106. assert.notOk(col.has(outsider));
  107. assert.notOk(col.has(outsider.id));
  108. assert.notOk(col.has(outsider.cid));
  109. });
  110. QUnit.test('update index when id changes', function(assert) {
  111. assert.expect(4);
  112. var collection = new Backbone.Collection();
  113. collection.add([
  114. {id: 0, name: 'one'},
  115. {id: 1, name: 'two'}
  116. ]);
  117. var one = collection.get(0);
  118. assert.equal(one.get('name'), 'one');
  119. collection.on('change:name', function(model) { assert.ok(this.get(model)); });
  120. one.set({name: 'dalmatians', id: 101});
  121. assert.equal(collection.get(0), null);
  122. assert.equal(collection.get(101).get('name'), 'dalmatians');
  123. });
  124. QUnit.test('at', function(assert) {
  125. assert.expect(2);
  126. assert.equal(col.at(2), c);
  127. assert.equal(col.at(-2), c);
  128. });
  129. QUnit.test('pluck', function(assert) {
  130. assert.expect(1);
  131. assert.equal(col.pluck('label').join(' '), 'a b c d');
  132. });
  133. QUnit.test('add', function(assert) {
  134. assert.expect(14);
  135. var added, opts, secondAdded;
  136. added = opts = secondAdded = null;
  137. e = new Backbone.Model({id: 10, label: 'e'});
  138. otherCol.add(e);
  139. otherCol.on('add', function() {
  140. secondAdded = true;
  141. });
  142. col.on('add', function(model, collection, options){
  143. added = model.get('label');
  144. opts = options;
  145. });
  146. col.add(e, {amazing: true});
  147. assert.equal(added, 'e');
  148. assert.equal(col.length, 5);
  149. assert.equal(col.last(), e);
  150. assert.equal(otherCol.length, 1);
  151. assert.equal(secondAdded, null);
  152. assert.ok(opts.amazing);
  153. var f = new Backbone.Model({id: 20, label: 'f'});
  154. var g = new Backbone.Model({id: 21, label: 'g'});
  155. var h = new Backbone.Model({id: 22, label: 'h'});
  156. var atCol = new Backbone.Collection([f, g, h]);
  157. assert.equal(atCol.length, 3);
  158. atCol.add(e, {at: 1});
  159. assert.equal(atCol.length, 4);
  160. assert.equal(atCol.at(1), e);
  161. assert.equal(atCol.last(), h);
  162. var coll = new Backbone.Collection(new Array(2));
  163. var addCount = 0;
  164. coll.on('add', function(){
  165. addCount += 1;
  166. });
  167. coll.add([undefined, f, g]);
  168. assert.equal(coll.length, 5);
  169. assert.equal(addCount, 3);
  170. coll.add(new Array(4));
  171. assert.equal(coll.length, 9);
  172. assert.equal(addCount, 7);
  173. });
  174. QUnit.test('add multiple models', function(assert) {
  175. assert.expect(6);
  176. var collection = new Backbone.Collection([{at: 0}, {at: 1}, {at: 9}]);
  177. collection.add([{at: 2}, {at: 3}, {at: 4}, {at: 5}, {at: 6}, {at: 7}, {at: 8}], {at: 2});
  178. for (var i = 0; i <= 5; i++) {
  179. assert.equal(collection.at(i).get('at'), i);
  180. }
  181. });
  182. QUnit.test('add; at should have preference over comparator', function(assert) {
  183. assert.expect(1);
  184. var Col = Backbone.Collection.extend({
  185. comparator: function(m1, m2) {
  186. return m1.id > m2.id ? -1 : 1;
  187. }
  188. });
  189. var collection = new Col([{id: 2}, {id: 3}]);
  190. collection.add(new Backbone.Model({id: 1}), {at: 1});
  191. assert.equal(collection.pluck('id').join(' '), '3 1 2');
  192. });
  193. QUnit.test('add; at should add to the end if the index is out of bounds', function(assert) {
  194. assert.expect(1);
  195. var collection = new Backbone.Collection([{id: 2}, {id: 3}]);
  196. collection.add(new Backbone.Model({id: 1}), {at: 5});
  197. assert.equal(collection.pluck('id').join(' '), '2 3 1');
  198. });
  199. QUnit.test("can't add model to collection twice", function(assert) {
  200. var collection = new Backbone.Collection([{id: 1}, {id: 2}, {id: 1}, {id: 2}, {id: 3}]);
  201. assert.equal(collection.pluck('id').join(' '), '1 2 3');
  202. });
  203. QUnit.test("can't add different model with same id to collection twice", function(assert) {
  204. assert.expect(1);
  205. var collection = new Backbone.Collection;
  206. collection.unshift({id: 101});
  207. collection.add({id: 101});
  208. assert.equal(collection.length, 1);
  209. });
  210. QUnit.test('merge in duplicate models with {merge: true}', function(assert) {
  211. assert.expect(3);
  212. var collection = new Backbone.Collection;
  213. collection.add([{id: 1, name: 'Moe'}, {id: 2, name: 'Curly'}, {id: 3, name: 'Larry'}]);
  214. collection.add({id: 1, name: 'Moses'});
  215. assert.equal(collection.first().get('name'), 'Moe');
  216. collection.add({id: 1, name: 'Moses'}, {merge: true});
  217. assert.equal(collection.first().get('name'), 'Moses');
  218. collection.add({id: 1, name: 'Tim'}, {merge: true, silent: true});
  219. assert.equal(collection.first().get('name'), 'Tim');
  220. });
  221. QUnit.test('add model to multiple collections', function(assert) {
  222. assert.expect(10);
  223. var counter = 0;
  224. var m = new Backbone.Model({id: 10, label: 'm'});
  225. m.on('add', function(model, collection) {
  226. counter++;
  227. assert.equal(m, model);
  228. if (counter > 1) {
  229. assert.equal(collection, col2);
  230. } else {
  231. assert.equal(collection, col1);
  232. }
  233. });
  234. var col1 = new Backbone.Collection([]);
  235. col1.on('add', function(model, collection) {
  236. assert.equal(m, model);
  237. assert.equal(col1, collection);
  238. });
  239. var col2 = new Backbone.Collection([]);
  240. col2.on('add', function(model, collection) {
  241. assert.equal(m, model);
  242. assert.equal(col2, collection);
  243. });
  244. col1.add(m);
  245. assert.equal(m.collection, col1);
  246. col2.add(m);
  247. assert.equal(m.collection, col1);
  248. });
  249. QUnit.test('add model with parse', function(assert) {
  250. assert.expect(1);
  251. var Model = Backbone.Model.extend({
  252. parse: function(obj) {
  253. obj.value += 1;
  254. return obj;
  255. }
  256. });
  257. var Col = Backbone.Collection.extend({model: Model});
  258. var collection = new Col;
  259. collection.add({value: 1}, {parse: true});
  260. assert.equal(collection.at(0).get('value'), 2);
  261. });
  262. QUnit.test('add with parse and merge', function(assert) {
  263. var collection = new Backbone.Collection();
  264. collection.parse = function(attrs) {
  265. return _.map(attrs, function(model) {
  266. if (model.model) return model.model;
  267. return model;
  268. });
  269. };
  270. collection.add({id: 1});
  271. collection.add({model: {id: 1, name: 'Alf'}}, {parse: true, merge: true});
  272. assert.equal(collection.first().get('name'), 'Alf');
  273. });
  274. QUnit.test('add model to collection with sort()-style comparator', function(assert) {
  275. assert.expect(3);
  276. var collection = new Backbone.Collection;
  277. collection.comparator = function(m1, m2) {
  278. return m1.get('name') < m2.get('name') ? -1 : 1;
  279. };
  280. var tom = new Backbone.Model({name: 'Tom'});
  281. var rob = new Backbone.Model({name: 'Rob'});
  282. var tim = new Backbone.Model({name: 'Tim'});
  283. collection.add(tom);
  284. collection.add(rob);
  285. collection.add(tim);
  286. assert.equal(collection.indexOf(rob), 0);
  287. assert.equal(collection.indexOf(tim), 1);
  288. assert.equal(collection.indexOf(tom), 2);
  289. });
  290. QUnit.test('comparator that depends on `this`', function(assert) {
  291. assert.expect(2);
  292. var collection = new Backbone.Collection;
  293. collection.negative = function(num) {
  294. return -num;
  295. };
  296. collection.comparator = function(model) {
  297. return this.negative(model.id);
  298. };
  299. collection.add([{id: 1}, {id: 2}, {id: 3}]);
  300. assert.deepEqual(collection.pluck('id'), [3, 2, 1]);
  301. collection.comparator = function(m1, m2) {
  302. return this.negative(m2.id) - this.negative(m1.id);
  303. };
  304. collection.sort();
  305. assert.deepEqual(collection.pluck('id'), [1, 2, 3]);
  306. });
  307. QUnit.test('remove', function(assert) {
  308. assert.expect(12);
  309. var removed = null;
  310. var result = null;
  311. col.on('remove', function(model, collection, options) {
  312. removed = model.get('label');
  313. assert.equal(options.index, 3);
  314. assert.equal(collection.get(model), undefined, '#3693: model cannot be fetched from collection');
  315. });
  316. result = col.remove(d);
  317. assert.equal(removed, 'd');
  318. assert.strictEqual(result, d);
  319. //if we try to remove d again, it's not going to actually get removed
  320. result = col.remove(d);
  321. assert.strictEqual(result, undefined);
  322. assert.equal(col.length, 3);
  323. assert.equal(col.first(), a);
  324. col.off();
  325. result = col.remove([c, d]);
  326. assert.equal(result.length, 1, 'only returns removed models');
  327. assert.equal(result[0], c, 'only returns removed models');
  328. result = col.remove([c, b]);
  329. assert.equal(result.length, 1, 'only returns removed models');
  330. assert.equal(result[0], b, 'only returns removed models');
  331. result = col.remove([]);
  332. assert.deepEqual(result, [], 'returns empty array when nothing removed');
  333. });
  334. QUnit.test('add and remove return values', function(assert) {
  335. assert.expect(13);
  336. var Even = Backbone.Model.extend({
  337. validate: function(attrs) {
  338. if (attrs.id % 2 !== 0) return 'odd';
  339. }
  340. });
  341. var collection = new Backbone.Collection;
  342. collection.model = Even;
  343. var list = collection.add([{id: 2}, {id: 4}], {validate: true});
  344. assert.equal(list.length, 2);
  345. assert.ok(list[0] instanceof Backbone.Model);
  346. assert.equal(list[1], collection.last());
  347. assert.equal(list[1].get('id'), 4);
  348. list = collection.add([{id: 3}, {id: 6}], {validate: true});
  349. assert.equal(collection.length, 3);
  350. assert.equal(list[0], false);
  351. assert.equal(list[1].get('id'), 6);
  352. var result = collection.add({id: 6});
  353. assert.equal(result.cid, list[1].cid);
  354. result = collection.remove({id: 6});
  355. assert.equal(collection.length, 2);
  356. assert.equal(result.id, 6);
  357. list = collection.remove([{id: 2}, {id: 8}]);
  358. assert.equal(collection.length, 1);
  359. assert.equal(list[0].get('id'), 2);
  360. assert.equal(list[1], null);
  361. });
  362. QUnit.test('shift and pop', function(assert) {
  363. assert.expect(2);
  364. var collection = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
  365. assert.equal(collection.shift().get('a'), 'a');
  366. assert.equal(collection.pop().get('c'), 'c');
  367. });
  368. QUnit.test('slice', function(assert) {
  369. assert.expect(2);
  370. var collection = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
  371. var array = collection.slice(1, 3);
  372. assert.equal(array.length, 2);
  373. assert.equal(array[0].get('b'), 'b');
  374. });
  375. QUnit.test('events are unbound on remove', function(assert) {
  376. assert.expect(3);
  377. var counter = 0;
  378. var dj = new Backbone.Model();
  379. var emcees = new Backbone.Collection([dj]);
  380. emcees.on('change', function(){ counter++; });
  381. dj.set({name: 'Kool'});
  382. assert.equal(counter, 1);
  383. emcees.reset([]);
  384. assert.equal(dj.collection, undefined);
  385. dj.set({name: 'Shadow'});
  386. assert.equal(counter, 1);
  387. });
  388. QUnit.test('remove in multiple collections', function(assert) {
  389. assert.expect(7);
  390. var modelData = {
  391. id: 5,
  392. title: 'Othello'
  393. };
  394. var passed = false;
  395. var m1 = new Backbone.Model(modelData);
  396. var m2 = new Backbone.Model(modelData);
  397. m2.on('remove', function() {
  398. passed = true;
  399. });
  400. var col1 = new Backbone.Collection([m1]);
  401. var col2 = new Backbone.Collection([m2]);
  402. assert.notEqual(m1, m2);
  403. assert.ok(col1.length === 1);
  404. assert.ok(col2.length === 1);
  405. col1.remove(m1);
  406. assert.equal(passed, false);
  407. assert.ok(col1.length === 0);
  408. col2.remove(m1);
  409. assert.ok(col2.length === 0);
  410. assert.equal(passed, true);
  411. });
  412. QUnit.test('remove same model in multiple collection', function(assert) {
  413. assert.expect(16);
  414. var counter = 0;
  415. var m = new Backbone.Model({id: 5, title: 'Othello'});
  416. m.on('remove', function(model, collection) {
  417. counter++;
  418. assert.equal(m, model);
  419. if (counter > 1) {
  420. assert.equal(collection, col1);
  421. } else {
  422. assert.equal(collection, col2);
  423. }
  424. });
  425. var col1 = new Backbone.Collection([m]);
  426. col1.on('remove', function(model, collection) {
  427. assert.equal(m, model);
  428. assert.equal(col1, collection);
  429. });
  430. var col2 = new Backbone.Collection([m]);
  431. col2.on('remove', function(model, collection) {
  432. assert.equal(m, model);
  433. assert.equal(col2, collection);
  434. });
  435. assert.equal(col1, m.collection);
  436. col2.remove(m);
  437. assert.ok(col2.length === 0);
  438. assert.ok(col1.length === 1);
  439. assert.equal(counter, 1);
  440. assert.equal(col1, m.collection);
  441. col1.remove(m);
  442. assert.equal(null, m.collection);
  443. assert.ok(col1.length === 0);
  444. assert.equal(counter, 2);
  445. });
  446. QUnit.test('model destroy removes from all collections', function(assert) {
  447. assert.expect(3);
  448. var m = new Backbone.Model({id: 5, title: 'Othello'});
  449. m.sync = function(method, model, options) { options.success(); };
  450. var col1 = new Backbone.Collection([m]);
  451. var col2 = new Backbone.Collection([m]);
  452. m.destroy();
  453. assert.ok(col1.length === 0);
  454. assert.ok(col2.length === 0);
  455. assert.equal(undefined, m.collection);
  456. });
  457. QUnit.test('Collection: non-persisted model destroy removes from all collections', function(assert) {
  458. assert.expect(3);
  459. var m = new Backbone.Model({title: 'Othello'});
  460. m.sync = function(method, model, options) { throw 'should not be called'; };
  461. var col1 = new Backbone.Collection([m]);
  462. var col2 = new Backbone.Collection([m]);
  463. m.destroy();
  464. assert.ok(col1.length === 0);
  465. assert.ok(col2.length === 0);
  466. assert.equal(undefined, m.collection);
  467. });
  468. QUnit.test('fetch', function(assert) {
  469. assert.expect(4);
  470. var collection = new Backbone.Collection;
  471. collection.url = '/test';
  472. collection.fetch();
  473. assert.equal(this.syncArgs.method, 'read');
  474. assert.equal(this.syncArgs.model, collection);
  475. assert.equal(this.syncArgs.options.parse, true);
  476. collection.fetch({parse: false});
  477. assert.equal(this.syncArgs.options.parse, false);
  478. });
  479. QUnit.test('fetch with an error response triggers an error event', function(assert) {
  480. assert.expect(1);
  481. var collection = new Backbone.Collection();
  482. collection.on('error', function() {
  483. assert.ok(true);
  484. });
  485. collection.sync = function(method, model, options) { options.error(); };
  486. collection.fetch();
  487. });
  488. QUnit.test('#3283 - fetch with an error response calls error with context', function(assert) {
  489. assert.expect(1);
  490. var collection = new Backbone.Collection();
  491. var obj = {};
  492. var options = {
  493. context: obj,
  494. error: function() {
  495. assert.equal(this, obj);
  496. }
  497. };
  498. collection.sync = function(method, model, opts) {
  499. opts.error.call(opts.context);
  500. };
  501. collection.fetch(options);
  502. });
  503. QUnit.test('ensure fetch only parses once', function(assert) {
  504. assert.expect(1);
  505. var collection = new Backbone.Collection;
  506. var counter = 0;
  507. collection.parse = function(models) {
  508. counter++;
  509. return models;
  510. };
  511. collection.url = '/test';
  512. collection.fetch();
  513. this.syncArgs.options.success([]);
  514. assert.equal(counter, 1);
  515. });
  516. QUnit.test('create', function(assert) {
  517. assert.expect(4);
  518. var collection = new Backbone.Collection;
  519. collection.url = '/test';
  520. var model = collection.create({label: 'f'}, {wait: true});
  521. assert.equal(this.syncArgs.method, 'create');
  522. assert.equal(this.syncArgs.model, model);
  523. assert.equal(model.get('label'), 'f');
  524. assert.equal(model.collection, collection);
  525. });
  526. QUnit.test('create with validate:true enforces validation', function(assert) {
  527. assert.expect(3);
  528. var ValidatingModel = Backbone.Model.extend({
  529. validate: function(attrs) {
  530. return 'fail';
  531. }
  532. });
  533. var ValidatingCollection = Backbone.Collection.extend({
  534. model: ValidatingModel
  535. });
  536. var collection = new ValidatingCollection();
  537. collection.on('invalid', function(coll, error, options) {
  538. assert.equal(error, 'fail');
  539. assert.equal(options.validationError, 'fail');
  540. });
  541. assert.equal(collection.create({foo: 'bar'}, {validate: true}), false);
  542. });
  543. QUnit.test('create will pass extra options to success callback', function(assert) {
  544. assert.expect(1);
  545. var Model = Backbone.Model.extend({
  546. sync: function(method, model, options) {
  547. _.extend(options, {specialSync: true});
  548. return Backbone.Model.prototype.sync.call(this, method, model, options);
  549. }
  550. });
  551. var Collection = Backbone.Collection.extend({
  552. model: Model,
  553. url: '/test'
  554. });
  555. var collection = new Collection;
  556. var success = function(model, response, options) {
  557. assert.ok(options.specialSync, 'Options were passed correctly to callback');
  558. };
  559. collection.create({}, {success: success});
  560. this.ajaxSettings.success();
  561. });
  562. QUnit.test('create with wait:true should not call collection.parse', function(assert) {
  563. assert.expect(0);
  564. var Collection = Backbone.Collection.extend({
  565. url: '/test',
  566. parse: function() {
  567. assert.ok(false);
  568. }
  569. });
  570. var collection = new Collection;
  571. collection.create({}, {wait: true});
  572. this.ajaxSettings.success();
  573. });
  574. QUnit.test('a failing create returns model with errors', function(assert) {
  575. var ValidatingModel = Backbone.Model.extend({
  576. validate: function(attrs) {
  577. return 'fail';
  578. }
  579. });
  580. var ValidatingCollection = Backbone.Collection.extend({
  581. model: ValidatingModel
  582. });
  583. var collection = new ValidatingCollection();
  584. var m = collection.create({foo: 'bar'});
  585. assert.equal(m.validationError, 'fail');
  586. assert.equal(collection.length, 1);
  587. });
  588. QUnit.test('initialize', function(assert) {
  589. assert.expect(1);
  590. var Collection = Backbone.Collection.extend({
  591. initialize: function() {
  592. this.one = 1;
  593. }
  594. });
  595. var coll = new Collection;
  596. assert.equal(coll.one, 1);
  597. });
  598. QUnit.test('preinitialize', function(assert) {
  599. assert.expect(1);
  600. var Collection = Backbone.Collection.extend({
  601. preinitialize: function() {
  602. this.one = 1;
  603. }
  604. });
  605. var coll = new Collection;
  606. assert.equal(coll.one, 1);
  607. });
  608. QUnit.test('preinitialize occurs before the collection is set up', function(assert) {
  609. assert.expect(2);
  610. var Collection = Backbone.Collection.extend({
  611. preinitialize: function() {
  612. assert.notEqual(this.model, FooModel);
  613. }
  614. });
  615. var FooModel = Backbone.Model.extend({id: 'foo'});
  616. var coll = new Collection({}, {
  617. model: FooModel
  618. });
  619. assert.equal(coll.model, FooModel);
  620. });
  621. QUnit.test('toJSON', function(assert) {
  622. assert.expect(1);
  623. assert.equal(JSON.stringify(col), '[{"id":3,"label":"a"},{"id":2,"label":"b"},{"id":1,"label":"c"},{"id":0,"label":"d"}]');
  624. });
  625. QUnit.test('where and findWhere', function(assert) {
  626. assert.expect(8);
  627. var model = new Backbone.Model({a: 1});
  628. var coll = new Backbone.Collection([
  629. model,
  630. {a: 1},
  631. {a: 1, b: 2},
  632. {a: 2, b: 2},
  633. {a: 3}
  634. ]);
  635. assert.equal(coll.where({a: 1}).length, 3);
  636. assert.equal(coll.where({a: 2}).length, 1);
  637. assert.equal(coll.where({a: 3}).length, 1);
  638. assert.equal(coll.where({b: 1}).length, 0);
  639. assert.equal(coll.where({b: 2}).length, 2);
  640. assert.equal(coll.where({a: 1, b: 2}).length, 1);
  641. assert.equal(coll.findWhere({a: 1}), model);
  642. assert.equal(coll.findWhere({a: 4}), void 0);
  643. });
  644. QUnit.test('mixin', function(assert) {
  645. Backbone.Collection.mixin({
  646. sum: function(models, iteratee) {
  647. return _.reduce(models, function(s, m) {
  648. return s + iteratee(m);
  649. }, 0);
  650. }
  651. });
  652. var coll = new Backbone.Collection([
  653. {a: 1},
  654. {a: 1, b: 2},
  655. {a: 2, b: 2},
  656. {a: 3}
  657. ]);
  658. assert.equal(coll.sum(function(m) {
  659. return m.get('a');
  660. }), 7);
  661. });
  662. QUnit.test('Underscore methods', function(assert) {
  663. assert.expect(21);
  664. assert.equal(col.map(function(model){ return model.get('label'); }).join(' '), 'a b c d');
  665. assert.equal(col.some(function(model){ return model.id === 100; }), false);
  666. assert.equal(col.some(function(model){ return model.id === 0; }), true);
  667. assert.equal(col.reduce(function(m1, m2) {return m1.id > m2.id ? m1 : m2;}).id, 3);
  668. assert.equal(col.reduceRight(function(m1, m2) {return m1.id > m2.id ? m1 : m2;}).id, 3);
  669. assert.equal(col.indexOf(b), 1);
  670. assert.equal(col.size(), 4);
  671. assert.equal(col.rest().length, 3);
  672. assert.ok(!_.includes(col.rest(), a));
  673. assert.ok(_.includes(col.rest(), d));
  674. assert.ok(!col.isEmpty());
  675. assert.ok(!_.includes(col.without(d), d));
  676. var wrapped = col.chain();
  677. assert.equal(wrapped.map('id').max().value(), 3);
  678. assert.equal(wrapped.map('id').min().value(), 0);
  679. assert.deepEqual(wrapped
  680. .filter(function(o){ return o.id % 2 === 0; })
  681. .map(function(o){ return o.id * 2; })
  682. .value(),
  683. [4, 0]);
  684. assert.deepEqual(col.difference([c, d]), [a, b]);
  685. assert.ok(col.includes(col.sample()));
  686. var first = col.first();
  687. assert.deepEqual(col.groupBy(function(model){ return model.id; })[first.id], [first]);
  688. assert.deepEqual(col.countBy(function(model){ return model.id; }), {0: 1, 1: 1, 2: 1, 3: 1});
  689. assert.deepEqual(col.sortBy(function(model){ return model.id; })[0], col.at(3));
  690. assert.ok(col.indexBy('id')[first.id] === first);
  691. });
  692. QUnit.test('Underscore methods with object-style and property-style iteratee', function(assert) {
  693. assert.expect(26);
  694. var model = new Backbone.Model({a: 4, b: 1, e: 3});
  695. var coll = new Backbone.Collection([
  696. {a: 1, b: 1},
  697. {a: 2, b: 1, c: 1},
  698. {a: 3, b: 1},
  699. model
  700. ]);
  701. assert.equal(coll.find({a: 0}), undefined);
  702. assert.deepEqual(coll.find({a: 4}), model);
  703. assert.equal(coll.find('d'), undefined);
  704. assert.deepEqual(coll.find('e'), model);
  705. assert.equal(coll.filter({a: 0}), false);
  706. assert.deepEqual(coll.filter({a: 4}), [model]);
  707. assert.equal(coll.some({a: 0}), false);
  708. assert.equal(coll.some({a: 1}), true);
  709. assert.equal(coll.reject({a: 0}).length, 4);
  710. assert.deepEqual(coll.reject({a: 4}), _.without(coll.models, model));
  711. assert.equal(coll.every({a: 0}), false);
  712. assert.equal(coll.every({b: 1}), true);
  713. assert.deepEqual(coll.partition({a: 0})[0], []);
  714. assert.deepEqual(coll.partition({a: 0})[1], coll.models);
  715. assert.deepEqual(coll.partition({a: 4})[0], [model]);
  716. assert.deepEqual(coll.partition({a: 4})[1], _.without(coll.models, model));
  717. assert.deepEqual(coll.map({a: 2}), [false, true, false, false]);
  718. assert.deepEqual(coll.map('a'), [1, 2, 3, 4]);
  719. assert.deepEqual(coll.sortBy('a')[3], model);
  720. assert.deepEqual(coll.sortBy('e')[0], model);
  721. assert.deepEqual(coll.countBy({a: 4}), {false: 3, true: 1});
  722. assert.deepEqual(coll.countBy('d'), {undefined: 4});
  723. assert.equal(coll.findIndex({b: 1}), 0);
  724. assert.equal(coll.findIndex({b: 9}), -1);
  725. assert.equal(coll.findLastIndex({b: 1}), 3);
  726. assert.equal(coll.findLastIndex({b: 9}), -1);
  727. });
  728. QUnit.test('reset', function(assert) {
  729. assert.expect(16);
  730. var resetCount = 0;
  731. var models = col.models;
  732. col.on('reset', function() { resetCount += 1; });
  733. col.reset([]);
  734. assert.equal(resetCount, 1);
  735. assert.equal(col.length, 0);
  736. assert.equal(col.last(), null);
  737. col.reset(models);
  738. assert.equal(resetCount, 2);
  739. assert.equal(col.length, 4);
  740. assert.equal(col.last(), d);
  741. col.reset(_.map(models, function(m){ return m.attributes; }));
  742. assert.equal(resetCount, 3);
  743. assert.equal(col.length, 4);
  744. assert.ok(col.last() !== d);
  745. assert.ok(_.isEqual(col.last().attributes, d.attributes));
  746. col.reset();
  747. assert.equal(col.length, 0);
  748. assert.equal(resetCount, 4);
  749. var f = new Backbone.Model({id: 20, label: 'f'});
  750. col.reset([undefined, f]);
  751. assert.equal(col.length, 2);
  752. assert.equal(resetCount, 5);
  753. col.reset(new Array(4));
  754. assert.equal(col.length, 4);
  755. assert.equal(resetCount, 6);
  756. });
  757. QUnit.test('reset with different values', function(assert) {
  758. var collection = new Backbone.Collection({id: 1});
  759. collection.reset({id: 1, a: 1});
  760. assert.equal(collection.get(1).get('a'), 1);
  761. });
  762. QUnit.test('same references in reset', function(assert) {
  763. var model = new Backbone.Model({id: 1});
  764. var collection = new Backbone.Collection({id: 1});
  765. collection.reset(model);
  766. assert.equal(collection.get(1), model);
  767. });
  768. QUnit.test('reset passes caller options', function(assert) {
  769. assert.expect(3);
  770. var Model = Backbone.Model.extend({
  771. initialize: function(attrs, options) {
  772. this.modelParameter = options.modelParameter;
  773. }
  774. });
  775. var collection = new (Backbone.Collection.extend({model: Model}))();
  776. collection.reset([{astring: 'green', anumber: 1}, {astring: 'blue', anumber: 2}], {modelParameter: 'model parameter'});
  777. assert.equal(collection.length, 2);
  778. collection.each(function(model) {
  779. assert.equal(model.modelParameter, 'model parameter');
  780. });
  781. });
  782. QUnit.test('reset does not alter options by reference', function(assert) {
  783. assert.expect(2);
  784. var collection = new Backbone.Collection([{id: 1}]);
  785. var origOpts = {};
  786. collection.on('reset', function(coll, opts){
  787. assert.equal(origOpts.previousModels, undefined);
  788. assert.equal(opts.previousModels[0].id, 1);
  789. });
  790. collection.reset([], origOpts);
  791. });
  792. QUnit.test('trigger custom events on models', function(assert) {
  793. assert.expect(1);
  794. var fired = null;
  795. a.on('custom', function() { fired = true; });
  796. a.trigger('custom');
  797. assert.equal(fired, true);
  798. });
  799. QUnit.test('add does not alter arguments', function(assert) {
  800. assert.expect(2);
  801. var attrs = {};
  802. var models = [attrs];
  803. new Backbone.Collection().add(models);
  804. assert.equal(models.length, 1);
  805. assert.ok(attrs === models[0]);
  806. });
  807. QUnit.test('#714: access `model.collection` in a brand new model.', function(assert) {
  808. assert.expect(2);
  809. var collection = new Backbone.Collection;
  810. collection.url = '/test';
  811. var Model = Backbone.Model.extend({
  812. set: function(attrs) {
  813. assert.equal(attrs.prop, 'value');
  814. assert.equal(this.collection, collection);
  815. return this;
  816. }
  817. });
  818. collection.model = Model;
  819. collection.create({prop: 'value'});
  820. });
  821. QUnit.test('#574, remove its own reference to the .models array.', function(assert) {
  822. assert.expect(2);
  823. var collection = new Backbone.Collection([
  824. {id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}
  825. ]);
  826. assert.equal(collection.length, 6);
  827. collection.remove(collection.models);
  828. assert.equal(collection.length, 0);
  829. });
  830. QUnit.test('#861, adding models to a collection which do not pass validation, with validate:true', function(assert) {
  831. assert.expect(2);
  832. var Model = Backbone.Model.extend({
  833. validate: function(attrs) {
  834. if (attrs.id === 3) return "id can't be 3";
  835. }
  836. });
  837. var Collection = Backbone.Collection.extend({
  838. model: Model
  839. });
  840. var collection = new Collection;
  841. collection.on('invalid', function() { assert.ok(true); });
  842. collection.add([{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}], {validate: true});
  843. assert.deepEqual(collection.pluck('id'), [1, 2, 4, 5, 6]);
  844. });
  845. QUnit.test('Invalid models are discarded with validate:true.', function(assert) {
  846. assert.expect(5);
  847. var collection = new Backbone.Collection;
  848. collection.on('test', function() { assert.ok(true); });
  849. collection.model = Backbone.Model.extend({
  850. validate: function(attrs){ if (!attrs.valid) return 'invalid'; }
  851. });
  852. var model = new collection.model({id: 1, valid: true});
  853. collection.add([model, {id: 2}], {validate: true});
  854. model.trigger('test');
  855. assert.ok(collection.get(model.cid));
  856. assert.ok(collection.get(1));
  857. assert.ok(!collection.get(2));
  858. assert.equal(collection.length, 1);
  859. });
  860. QUnit.test('multiple copies of the same model', function(assert) {
  861. assert.expect(3);
  862. var collection = new Backbone.Collection();
  863. var model = new Backbone.Model();
  864. collection.add([model, model]);
  865. assert.equal(collection.length, 1);
  866. collection.add([{id: 1}, {id: 1}]);
  867. assert.equal(collection.length, 2);
  868. assert.equal(collection.last().id, 1);
  869. });
  870. QUnit.test('#964 - collection.get return inconsistent', function(assert) {
  871. assert.expect(2);
  872. var collection = new Backbone.Collection();
  873. assert.ok(collection.get(null) === undefined);
  874. assert.ok(collection.get() === undefined);
  875. });
  876. QUnit.test('#1112 - passing options.model sets collection.model', function(assert) {
  877. assert.expect(2);
  878. var Model = Backbone.Model.extend({});
  879. var collection = new Backbone.Collection([{id: 1}], {model: Model});
  880. assert.ok(collection.model === Model);
  881. assert.ok(collection.at(0) instanceof Model);
  882. });
  883. QUnit.test('null and undefined are invalid ids.', function(assert) {
  884. assert.expect(2);
  885. var model = new Backbone.Model({id: 1});
  886. var collection = new Backbone.Collection([model]);
  887. model.set({id: null});
  888. assert.ok(!collection.get('null'));
  889. model.set({id: 1});
  890. model.set({id: undefined});
  891. assert.ok(!collection.get('undefined'));
  892. });
  893. QUnit.test('falsy comparator', function(assert) {
  894. assert.expect(4);
  895. var Col = Backbone.Collection.extend({
  896. comparator: function(model){ return model.id; }
  897. });
  898. var collection = new Col();
  899. var colFalse = new Col(null, {comparator: false});
  900. var colNull = new Col(null, {comparator: null});
  901. var colUndefined = new Col(null, {comparator: undefined});
  902. assert.ok(collection.comparator);
  903. assert.ok(!colFalse.comparator);
  904. assert.ok(!colNull.comparator);
  905. assert.ok(colUndefined.comparator);
  906. });
  907. QUnit.test('#1355 - `options` is passed to success callbacks', function(assert) {
  908. assert.expect(2);
  909. var m = new Backbone.Model({x: 1});
  910. var collection = new Backbone.Collection();
  911. var opts = {
  912. opts: true,
  913. success: function(coll, resp, options) {
  914. assert.ok(options.opts);
  915. }
  916. };
  917. collection.sync = m.sync = function( method, coll, options ){
  918. options.success({});
  919. };
  920. collection.fetch(opts);
  921. collection.create(m, opts);
  922. });
  923. QUnit.test("#1412 - Trigger 'request' and 'sync' events.", function(assert) {
  924. assert.expect(4);
  925. var collection = new Backbone.Collection;
  926. collection.url = '/test';
  927. Backbone.ajax = function(settings){ settings.success(); };
  928. collection.on('request', function(obj, xhr, options) {
  929. assert.ok(obj === collection, "collection has correct 'request' event after fetching");
  930. });
  931. collection.on('sync', function(obj, response, options) {
  932. assert.ok(obj === collection, "collection has correct 'sync' event after fetching");
  933. });
  934. collection.fetch();
  935. collection.off();
  936. collection.on('request', function(obj, xhr, options) {
  937. assert.ok(obj === collection.get(1), "collection has correct 'request' event after one of its models save");
  938. });
  939. collection.on('sync', function(obj, response, options) {
  940. assert.ok(obj === collection.get(1), "collection has correct 'sync' event after one of its models save");
  941. });
  942. collection.create({id: 1});
  943. collection.off();
  944. });
  945. QUnit.test('#3283 - fetch, create calls success with context', function(assert) {
  946. assert.expect(2);
  947. var collection = new Backbone.Collection;
  948. collection.url = '/test';
  949. Backbone.ajax = function(settings) {
  950. settings.success.call(settings.context);
  951. };
  952. var obj = {};
  953. var options = {
  954. context: obj,
  955. success: function() {
  956. assert.equal(this, obj);
  957. }
  958. };
  959. collection.fetch(options);
  960. collection.create({id: 1}, options);
  961. });
  962. QUnit.test('#1447 - create with wait adds model.', function(assert) {
  963. assert.expect(1);
  964. var collection = new Backbone.Collection;
  965. var model = new Backbone.Model;
  966. model.sync = function(method, m, options){ options.success(); };
  967. collection.on('add', function(){ assert.ok(true); });
  968. collection.create(model, {wait: true});
  969. });
  970. QUnit.test('#1448 - add sorts collection after merge.', function(assert) {
  971. assert.expect(1);
  972. var collection = new Backbone.Collection([
  973. {id: 1, x: 1},
  974. {id: 2, x: 2}
  975. ]);
  976. collection.comparator = function(model){ return model.get('x'); };
  977. collection.add({id: 1, x: 3}, {merge: true});
  978. assert.deepEqual(collection.pluck('id'), [2, 1]);
  979. });
  980. QUnit.test('#1655 - groupBy can be used with a string argument.', function(assert) {
  981. assert.expect(3);
  982. var collection = new Backbone.Collection([{x: 1}, {x: 2}]);
  983. var grouped = collection.groupBy('x');
  984. assert.strictEqual(_.keys(grouped).length, 2);
  985. assert.strictEqual(grouped[1][0].get('x'), 1);
  986. assert.strictEqual(grouped[2][0].get('x'), 2);
  987. });
  988. QUnit.test('#1655 - sortBy can be used with a string argument.', function(assert) {
  989. assert.expect(1);
  990. var collection = new Backbone.Collection([{x: 3}, {x: 1}, {x: 2}]);
  991. var values = _.map(collection.sortBy('x'), function(model) {
  992. return model.get('x');
  993. });
  994. assert.deepEqual(values, [1, 2, 3]);
  995. });
  996. QUnit.test('#1604 - Removal during iteration.', function(assert) {
  997. assert.expect(0);
  998. var collection = new Backbone.Collection([{}, {}]);
  999. collection.on('add', function() {
  1000. collection.at(0).destroy();
  1001. });
  1002. collection.add({}, {at: 0});
  1003. });
  1004. QUnit.test('#1638 - `sort` during `add` triggers correctly.', function(assert) {
  1005. var collection = new Backbone.Collection;
  1006. collection.comparator = function(model) { return model.get('x'); };
  1007. var added = [];
  1008. collection.on('add', function(model) {
  1009. model.set({x: 3});
  1010. collection.sort();
  1011. added.push(model.id);
  1012. });
  1013. collection.add([{id: 1, x: 1}, {id: 2, x: 2}]);
  1014. assert.deepEqual(added, [1, 2]);
  1015. });
  1016. QUnit.test('fetch parses models by default', function(assert) {
  1017. assert.expect(1);
  1018. var model = {};
  1019. var Collection = Backbone.Collection.extend({
  1020. url: 'test',
  1021. model: Backbone.Model.extend({
  1022. parse: function(resp) {
  1023. assert.strictEqual(resp, model);
  1024. }
  1025. })
  1026. });
  1027. new Collection().fetch();
  1028. this.ajaxSettings.success([model]);
  1029. });
  1030. QUnit.test("`sort` shouldn't always fire on `add`", function(assert) {
  1031. assert.expect(1);
  1032. var collection = new Backbone.Collection([{id: 1}, {id: 2}, {id: 3}], {
  1033. comparator: 'id'
  1034. });
  1035. collection.sort = function(){ assert.ok(true); };
  1036. collection.add([]);
  1037. collection.add({id: 1});
  1038. collection.add([{id: 2}, {id: 3}]);
  1039. collection.add({id: 4});
  1040. });
  1041. QUnit.test('#1407 parse option on constructor parses collection and models', function(assert) {
  1042. assert.expect(2);
  1043. var model = {
  1044. namespace: [{id: 1}, {id: 2}]
  1045. };
  1046. var Collection = Backbone.Collection.extend({
  1047. model: Backbone.Model.extend({
  1048. parse: function(m) {
  1049. m.name = 'test';
  1050. return m;
  1051. }
  1052. }),
  1053. parse: function(m) {
  1054. return m.namespace;
  1055. }
  1056. });
  1057. var collection = new Collection(model, {parse: true});
  1058. assert.equal(collection.length, 2);
  1059. assert.equal(collection.at(0).get('name'), 'test');
  1060. });
  1061. QUnit.test('#1407 parse option on reset parses collection and models', function(assert) {
  1062. assert.expect(2);
  1063. var model = {
  1064. namespace: [{id: 1}, {id: 2}]
  1065. };
  1066. var Collection = Backbone.Collection.extend({
  1067. model: Backbone.Model.extend({
  1068. parse: function(m) {
  1069. m.name = 'test';
  1070. return m;
  1071. }
  1072. }),
  1073. parse: function(m) {
  1074. return m.namespace;
  1075. }
  1076. });
  1077. var collection = new Collection();
  1078. collection.reset(model, {parse: true});
  1079. assert.equal(collection.length, 2);
  1080. assert.equal(collection.at(0).get('name'), 'test');
  1081. });
  1082. QUnit.test('Reset includes previous models in triggered event.', function(assert) {
  1083. assert.expect(1);
  1084. var model = new Backbone.Model();
  1085. var collection = new Backbone.Collection([model]);
  1086. collection.on('reset', function(coll, options) {
  1087. assert.deepEqual(options.previousModels, [model]);
  1088. });
  1089. collection.reset([]);
  1090. });
  1091. QUnit.test('set', function(assert) {
  1092. var m1 = new Backbone.Model();
  1093. var m2 = new Backbone.Model({id: 2});
  1094. var m3 = new Backbone.Model();
  1095. var collection = new Backbone.Collection([m1, m2]);
  1096. // Test add/change/remove events
  1097. collection.on('add', function(model) {
  1098. assert.strictEqual(model, m3);
  1099. });
  1100. collection.on('change', function(model) {
  1101. assert.strictEqual(model, m2);
  1102. });
  1103. collection.on('remove', function(model) {
  1104. assert.strictEqual(model, m1);
  1105. });
  1106. // remove: false doesn't remove any models
  1107. collection.set([], {remove: false});
  1108. assert.strictEqual(collection.length, 2);
  1109. // add: false doesn't add any models
  1110. collection.set([m1, m2, m3], {add: false});
  1111. assert.strictEqual(collection.length, 2);
  1112. // merge: false doesn't change any models
  1113. collection.set([m1, {id: 2, a: 1}], {merge: false});
  1114. assert.strictEqual(m2.get('a'), void 0);
  1115. // add: false, remove: false only merges existing models
  1116. collection.set([m1, {id: 2, a: 0}, m3, {id: 4}], {add: false, remove: false});
  1117. assert.strictEqual(collection.length, 2);
  1118. assert.strictEqual(m2.get('a'), 0);
  1119. // default options add/remove/merge as appropriate
  1120. collection.set([{id: 2, a: 1}, m3]);
  1121. assert.strictEqual(collection.length, 2);
  1122. assert.strictEqual(m2.get('a'), 1);
  1123. // Test removing models not passing an argument
  1124. collection.off('remove').on('remove', function(model) {
  1125. assert.ok(model === m2 || model === m3);
  1126. });
  1127. collection.set([]);
  1128. assert.strictEqual(collection.length, 0);
  1129. // Test null models on set doesn't clear collection
  1130. collection.off();
  1131. collection.set([{id: 1}]);
  1132. collection.set();
  1133. assert.strictEqual(collection.length, 1);
  1134. });
  1135. QUnit.test('set with only cids', function(assert) {
  1136. assert.expect(3);
  1137. var m1 = new Backbone.Model;
  1138. var m2 = new Backbone.Model;
  1139. var collection = new Backbone.Collection;
  1140. collection.set([m1, m2]);
  1141. assert.equal(collection.length, 2);
  1142. collection.set([m1]);
  1143. assert.equal(collection.length, 1);
  1144. collection.set([m1, m1, m1, m2, m2], {remove: false});
  1145. assert.equal(collection.length, 2);
  1146. });
  1147. QUnit.test('set with only idAttribute', function(assert) {
  1148. assert.expect(3);
  1149. var m1 = {_id: 1};
  1150. var m2 = {_id: 2};
  1151. var Col = Backbone.Collection.extend({
  1152. model: Backbone.Model.extend({
  1153. idAttribute: '_id'
  1154. })
  1155. });
  1156. var collection = new Col;
  1157. collection.set([m1, m2]);
  1158. assert.equal(collection.length, 2);
  1159. collection.set([m1]);
  1160. assert.equal(collection.length, 1);
  1161. collection.set([m1, m1, m1, m2, m2], {remove: false});
  1162. assert.equal(collection.length, 2);
  1163. });
  1164. QUnit.test('set + merge with default values defined', function(assert) {
  1165. var Model = Backbone.Model.extend({
  1166. defaults: {
  1167. key: 'value'
  1168. }
  1169. });
  1170. var m = new Model({id: 1});
  1171. var collection = new Backbone.Collection([m], {model: Model});
  1172. assert.equal(collection.first().get('key'), 'value');
  1173. collection.set({id: 1, key: 'other'});
  1174. assert.equal(collection.first().get('key'), 'other');
  1175. collection.set({id: 1, other: 'value'});
  1176. assert.equal(collection.first().get('key'), 'other');
  1177. assert.equal(collection.length, 1);
  1178. });
  1179. QUnit.test('merge without mutation', function(assert) {
  1180. var Model = Backbone.Model.extend({
  1181. initialize: function(attrs, options) {
  1182. if (attrs.child) {
  1183. this.set('child', new Model(attrs.child, options), options);
  1184. }
  1185. }
  1186. });
  1187. var Collection = Backbone.Collection.extend({model: Model});
  1188. var data = [{id: 1, child: {id: 2}}];
  1189. var collection = new Collection(data);
  1190. assert.equal(collection.first().id, 1);
  1191. collection.set(data);
  1192. assert.equal(collection.first().id, 1);
  1193. collection.set([{id: 2, child: {id: 2}}].concat(data));
  1194. assert.deepEqual(collection.pluck('id'), [2, 1]);
  1195. });
  1196. QUnit.test('`set` and model level `parse`', function(assert) {
  1197. var Model = Backbone.Model.extend({});
  1198. var Collection = Backbone.Collection.extend({
  1199. model: Model,
  1200. parse: function(res) { return _.map(res.models, 'model'); }
  1201. });
  1202. var model = new Model({id: 1});
  1203. var collection = new Collection(model);
  1204. collection.set({models: [
  1205. {model: {id: 1}},
  1206. {model: {id: 2}}
  1207. ]}, {parse: true});
  1208. assert.equal(collection.first(), model);
  1209. });
  1210. QUnit.test('`set` data is only parsed once', function(assert) {
  1211. var collection = new Backbone.Collection();
  1212. collection.model = Backbone.Model.extend({
  1213. parse: function(data) {
  1214. assert.equal(data.parsed, void 0);
  1215. data.parsed = true;
  1216. return data;
  1217. }
  1218. });
  1219. collection.set({}, {parse: true});
  1220. });
  1221. QUnit.test('`set` matches input order in the absence of a comparator', function(assert) {
  1222. var one = new Backbone.Model({id: 1});
  1223. var two = new Backbone.Model({id: 2});
  1224. var three = new Backbone.Model({id: 3});
  1225. var collection = new Backbone.Collection([one, two, three]);
  1226. collection.set([{id: 3}, {id: 2}, {id: 1}]);
  1227. assert.deepEqual(collection.models, [three, two, one]);
  1228. collection.set([{id: 1}, {id: 2}]);
  1229. assert.deepEqual(collection.models, [one, two]);
  1230. collection.set([two, three, one]);
  1231. assert.deepEqual(collection.models, [two, three, one]);
  1232. collection.set([{id: 1}, {id: 2}], {remove: false});
  1233. assert.deepEqual(collection.models, [two, three, one]);
  1234. collection.set([{id: 1}, {id: 2}, {id: 3}], {merge: false});
  1235. assert.deepEqual(collection.models, [one, two, three]);
  1236. collection.set([three, two, one, {id: 4}], {add: false});
  1237. assert.deepEqual(collection.models, [one, two, three]);
  1238. });
  1239. QUnit.test('#1894 - Push should not trigger a sort', function(assert) {
  1240. assert.expect(0);
  1241. var Collection = Backbone.Collection.extend({
  1242. comparator: 'id',
  1243. sort: function() { assert.ok(false); }
  1244. });
  1245. new Collection().push({id: 1});
  1246. });
  1247. QUnit.test('#2428 - push duplicate models, return the correct one', function(assert) {
  1248. assert.expect(1);
  1249. var collection = new Backbone.Collection;
  1250. var model1 = collection.push({id: 101});
  1251. var model2 = collection.push({id: 101});
  1252. assert.ok(model2.cid === model1.cid);
  1253. });
  1254. QUnit.test('`set` with non-normal id', function(assert) {
  1255. var Collection = Backbone.Collection.extend({
  1256. model: Backbone.Model.extend({idAttribute: '_id'})
  1257. });
  1258. var collection = new Collection({_id: 1});
  1259. collection.set([{_id: 1, a: 1}], {add: false});
  1260. assert.equal(collection.first().get('a'), 1);
  1261. });
  1262. QUnit.test('#1894 - `sort` can optionally be turned off', function(assert) {
  1263. assert.expect(0);
  1264. var Collection = Backbone.Collection.extend({
  1265. comparator: 'id',
  1266. sort: function() { assert.ok(false); }
  1267. });
  1268. new Collection().add({id: 1}, {sort: false});
  1269. });
  1270. QUnit.test('#1915 - `parse` data in the right order in `set`', function(assert) {
  1271. var collection = new (Backbone.Collection.extend({
  1272. parse: function(data) {
  1273. assert.strictEqual(data.status, 'ok');
  1274. return data.data;
  1275. }
  1276. }));
  1277. var res = {status: 'ok', data: [{id: 1}]};
  1278. collection.set(res, {parse: true});
  1279. });
  1280. QUnit.test('#1939 - `parse` is passed `options`', function(assert) {
  1281. var done = assert.async();
  1282. assert.expect(1);
  1283. var collection = new (Backbone.Collection.extend({
  1284. url: '/',
  1285. parse: function(data, options) {
  1286. assert.strictEqual(options.xhr.someHeader, 'headerValue');
  1287. return data;
  1288. }
  1289. }));
  1290. var ajax = Backbone.ajax;
  1291. Backbone.ajax = function(params) {
  1292. _.defer(params.success, []);
  1293. return {someHeader: 'headerValue'};
  1294. };
  1295. collection.fetch({
  1296. success: function() { done(); }
  1297. });
  1298. Backbone.ajax = ajax;
  1299. });
  1300. QUnit.test('fetch will pass extra options to success callback', function(assert) {
  1301. assert.expect(1);
  1302. var SpecialSyncCollection = Backbone.Collection.extend({
  1303. url: '/test',
  1304. sync: function(method, collection, options) {
  1305. _.extend(options, {specialSync: true});
  1306. return Backbone.Collection.prototype.sync.call(this, method, collection, options);
  1307. }
  1308. });
  1309. var collection = new SpecialSyncCollection();
  1310. var onSuccess = function(coll, resp, options) {
  1311. assert.ok(options.specialSync, 'Options were passed correctly to callback');
  1312. };
  1313. collection.fetch({success: onSuccess});
  1314. this.ajaxSettings.success();
  1315. });
  1316. QUnit.test('`add` only `sort`s when necessary', function(assert) {
  1317. assert.expect(2);
  1318. var collection = new (Backbone.Collection.extend({
  1319. comparator: 'a'
  1320. }))([{id: 1}, {id: 2}, {id: 3}]);
  1321. collection.on('sort', function() { assert.ok(true); });
  1322. collection.add({id: 4}); // do sort, new model
  1323. collection.add({id: 1, a: 1}, {merge: true}); // do sort, comparator change
  1324. collection.add({id: 1, b: 1}, {merge: true}); // don't sort, no comparator change
  1325. collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no comparator change
  1326. collection.add(collection.models); // don't sort, nothing new
  1327. collection.add(collection.models, {merge: true}); // don't sort
  1328. });
  1329. QUnit.test('`add` only `sort`s when necessary with comparator function', function(assert) {
  1330. assert.expect(3);
  1331. var collection = new (Backbone.Collection.extend({
  1332. comparator: function(m1, m2) {
  1333. return m1.get('a') > m2.get('a') ? 1 : m1.get('a') < m2.get('a') ? -1 : 0;
  1334. }
  1335. }))([{id: 1}, {id: 2}, {id: 3}]);
  1336. collection.on('sort', function() { assert.ok(true); });
  1337. collection.add({id: 4}); // do sort, new model
  1338. collection.add({id: 1, a: 1}, {merge: true}); // do sort, model change
  1339. collection.add({id: 1, b: 1}, {merge: true}); // do sort, model change
  1340. collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no model change
  1341. collection.add(collect

Large files files are truncated, but you can click here to view the full file