PageRenderTime 125ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/test/collection.js

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