PageRenderTime 27ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/test/collection.js

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