PageRenderTime 49ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/test/collection.js

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