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

/test/collection.js

https://github.com/aihua/backbone
JavaScript | 1674 lines | 1481 code | 184 blank | 9 comment | 14 complexity | 54a06bb208e4f5fa679144643c8a0dc4 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("create with wait:true should not call collection.parse", 0, function() {
  505. var Collection = Backbone.Collection.extend({
  506. url: '/test',
  507. parse: function () {
  508. ok(false);
  509. }
  510. });
  511. var collection = new Collection;
  512. collection.create({}, {wait: true});
  513. this.ajaxSettings.success();
  514. });
  515. test("a failing create returns model with errors", function() {
  516. var ValidatingModel = Backbone.Model.extend({
  517. validate: function(attrs) {
  518. return "fail";
  519. }
  520. });
  521. var ValidatingCollection = Backbone.Collection.extend({
  522. model: ValidatingModel
  523. });
  524. var col = new ValidatingCollection();
  525. var m = col.create({"foo":"bar"});
  526. equal(m.validationError, 'fail');
  527. equal(col.length, 1);
  528. });
  529. test("initialize", 1, function() {
  530. var Collection = Backbone.Collection.extend({
  531. initialize: function() {
  532. this.one = 1;
  533. }
  534. });
  535. var coll = new Collection;
  536. equal(coll.one, 1);
  537. });
  538. test("toJSON", 1, function() {
  539. equal(JSON.stringify(col), '[{"id":3,"label":"a"},{"id":2,"label":"b"},{"id":1,"label":"c"},{"id":0,"label":"d"}]');
  540. });
  541. test("where and findWhere", 8, function() {
  542. var model = new Backbone.Model({a: 1});
  543. var coll = new Backbone.Collection([
  544. model,
  545. {a: 1},
  546. {a: 1, b: 2},
  547. {a: 2, b: 2},
  548. {a: 3}
  549. ]);
  550. equal(coll.where({a: 1}).length, 3);
  551. equal(coll.where({a: 2}).length, 1);
  552. equal(coll.where({a: 3}).length, 1);
  553. equal(coll.where({b: 1}).length, 0);
  554. equal(coll.where({b: 2}).length, 2);
  555. equal(coll.where({a: 1, b: 2}).length, 1);
  556. equal(coll.findWhere({a: 1}), model);
  557. equal(coll.findWhere({a: 4}), void 0);
  558. });
  559. test("Underscore methods", 19, function() {
  560. equal(col.map(function(model){ return model.get('label'); }).join(' '), 'a b c d');
  561. equal(col.any(function(model){ return model.id === 100; }), false);
  562. equal(col.any(function(model){ return model.id === 0; }), true);
  563. equal(col.indexOf(b), 1);
  564. equal(col.size(), 4);
  565. equal(col.rest().length, 3);
  566. ok(!_.include(col.rest(), a));
  567. ok(_.include(col.rest(), d));
  568. ok(!col.isEmpty());
  569. ok(!_.include(col.without(d), d));
  570. equal(col.max(function(model){ return model.id; }).id, 3);
  571. equal(col.min(function(model){ return model.id; }).id, 0);
  572. deepEqual(col.chain()
  573. .filter(function(o){ return o.id % 2 === 0; })
  574. .map(function(o){ return o.id * 2; })
  575. .value(),
  576. [4, 0]);
  577. deepEqual(col.difference([c, d]), [a, b]);
  578. ok(col.include(col.sample()));
  579. var first = col.first();
  580. deepEqual(col.groupBy(function(model){ return model.id; })[first.id], [first]);
  581. deepEqual(col.countBy(function(model){ return model.id; }), {0: 1, 1: 1, 2: 1, 3: 1});
  582. deepEqual(col.sortBy(function(model){ return model.id; })[0], col.at(3));
  583. ok(col.indexBy('id')[first.id] === first);
  584. });
  585. test("Underscore methods with object-style and property-style iteratee", 22, function () {
  586. var model = new Backbone.Model({a: 4, b: 1, e: 3});
  587. var coll = new Backbone.Collection([
  588. {a: 1, b: 1},
  589. {a: 2, b: 1, c: 1},
  590. {a: 3, b: 1},
  591. model
  592. ]);
  593. equal(coll.find({a: 0}), undefined);
  594. deepEqual(coll.find({a: 4}), model);
  595. equal(coll.find('d'), undefined);
  596. deepEqual(coll.find('e'), model);
  597. equal(coll.filter({a: 0}), false);
  598. deepEqual(coll.filter({a: 4}), [model]);
  599. equal(coll.some({a: 0}), false);
  600. equal(coll.some({a: 1}), true);
  601. equal(coll.reject({a: 0}).length, 4);
  602. deepEqual(coll.reject({a: 4}), _.without(coll.models, model));
  603. equal(coll.every({a: 0}), false);
  604. equal(coll.every({b: 1}), true);
  605. deepEqual(coll.partition({a: 0})[0], []);
  606. deepEqual(coll.partition({a: 0})[1], coll.models);
  607. deepEqual(coll.partition({a: 4})[0], [model]);
  608. deepEqual(coll.partition({a: 4})[1], _.without(coll.models, model));
  609. deepEqual(coll.map({a: 2}), [false, true, false, false]);
  610. deepEqual(coll.map('a'), [1, 2, 3, 4]);
  611. deepEqual(coll.max('a'), model);
  612. deepEqual(coll.min('e'), model);
  613. deepEqual(coll.countBy({a: 4}), {'false': 3, 'true': 1});
  614. deepEqual(coll.countBy('d'), {'undefined': 4});
  615. });
  616. test("reset", 16, function() {
  617. var resetCount = 0;
  618. var models = col.models;
  619. col.on('reset', function() { resetCount += 1; });
  620. col.reset([]);
  621. equal(resetCount, 1);
  622. equal(col.length, 0);
  623. equal(col.last(), null);
  624. col.reset(models);
  625. equal(resetCount, 2);
  626. equal(col.length, 4);
  627. equal(col.last(), d);
  628. col.reset(_.map(models, function(m){ return m.attributes; }));
  629. equal(resetCount, 3);
  630. equal(col.length, 4);
  631. ok(col.last() !== d);
  632. ok(_.isEqual(col.last().attributes, d.attributes));
  633. col.reset();
  634. equal(col.length, 0);
  635. equal(resetCount, 4);
  636. var f = new Backbone.Model({id: 20, label : 'f'});
  637. col.reset([undefined, f]);
  638. equal(col.length, 2);
  639. equal(resetCount, 5);
  640. col.reset(new Array(4));
  641. equal(col.length, 4);
  642. equal(resetCount, 6);
  643. });
  644. test ("reset with different values", function(){
  645. var col = new Backbone.Collection({id: 1});
  646. col.reset({id: 1, a: 1});
  647. equal(col.get(1).get('a'), 1);
  648. });
  649. test("same references in reset", function() {
  650. var model = new Backbone.Model({id: 1});
  651. var collection = new Backbone.Collection({id: 1});
  652. collection.reset(model);
  653. equal(collection.get(1), model);
  654. });
  655. test("reset passes caller options", 3, function() {
  656. var Model = Backbone.Model.extend({
  657. initialize: function(attrs, options) {
  658. this.model_parameter = options.model_parameter;
  659. }
  660. });
  661. var col = new (Backbone.Collection.extend({ model: Model }))();
  662. col.reset([{ astring: "green", anumber: 1 }, { astring: "blue", anumber: 2 }], { model_parameter: 'model parameter' });
  663. equal(col.length, 2);
  664. col.each(function(model) {
  665. equal(model.model_parameter, 'model parameter');
  666. });
  667. });
  668. test("reset does not alter options by reference", 2, function() {
  669. var col = new Backbone.Collection([{id:1}]);
  670. var origOpts = {};
  671. col.on("reset", function(col, opts){
  672. equal(origOpts.previousModels, undefined);
  673. equal(opts.previousModels[0].id, 1);
  674. });
  675. col.reset([], origOpts);
  676. });
  677. test("trigger custom events on models", 1, function() {
  678. var fired = null;
  679. a.on("custom", function() { fired = true; });
  680. a.trigger("custom");
  681. equal(fired, true);
  682. });
  683. test("add does not alter arguments", 2, function(){
  684. var attrs = {};
  685. var models = [attrs];
  686. new Backbone.Collection().add(models);
  687. equal(models.length, 1);
  688. ok(attrs === models[0]);
  689. });
  690. test("#714: access `model.collection` in a brand new model.", 2, function() {
  691. var collection = new Backbone.Collection;
  692. collection.url = '/test';
  693. var Model = Backbone.Model.extend({
  694. set: function(attrs) {
  695. equal(attrs.prop, 'value');
  696. equal(this.collection, collection);
  697. return this;
  698. }
  699. });
  700. collection.model = Model;
  701. collection.create({prop: 'value'});
  702. });
  703. test("#574, remove its own reference to the .models array.", 2, function() {
  704. var col = new Backbone.Collection([
  705. {id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}
  706. ]);
  707. equal(col.length, 6);
  708. col.remove(col.models);
  709. equal(col.length, 0);
  710. });
  711. test("#861, adding models to a collection which do not pass validation, with validate:true", 2, function() {
  712. var Model = Backbone.Model.extend({
  713. validate: function(attrs) {
  714. if (attrs.id == 3) return "id can't be 3";
  715. }
  716. });
  717. var Collection = Backbone.Collection.extend({
  718. model: Model
  719. });
  720. var collection = new Collection;
  721. collection.on("invalid", function() { ok(true); });
  722. collection.add([{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}], {validate:true});
  723. deepEqual(collection.pluck("id"), [1, 2, 4, 5, 6]);
  724. });
  725. test("Invalid models are discarded with validate:true.", 5, function() {
  726. var collection = new Backbone.Collection;
  727. collection.on('test', function() { ok(true); });
  728. collection.model = Backbone.Model.extend({
  729. validate: function(attrs){ if (!attrs.valid) return 'invalid'; }
  730. });
  731. var model = new collection.model({id: 1, valid: true});
  732. collection.add([model, {id: 2}], {validate:true});
  733. model.trigger('test');
  734. ok(collection.get(model.cid));
  735. ok(collection.get(1));
  736. ok(!collection.get(2));
  737. equal(collection.length, 1);
  738. });
  739. test("multiple copies of the same model", 3, function() {
  740. var col = new Backbone.Collection();
  741. var model = new Backbone.Model();
  742. col.add([model, model]);
  743. equal(col.length, 1);
  744. col.add([{id: 1}, {id: 1}]);
  745. equal(col.length, 2);
  746. equal(col.last().id, 1);
  747. });
  748. test("#964 - collection.get return inconsistent", 2, function() {
  749. var c = new Backbone.Collection();
  750. ok(c.get(null) === undefined);
  751. ok(c.get() === undefined);
  752. });
  753. test("#1112 - passing options.model sets collection.model", 2, function() {
  754. var Model = Backbone.Model.extend({});
  755. var c = new Backbone.Collection([{id: 1}], {model: Model});
  756. ok(c.model === Model);
  757. ok(c.at(0) instanceof Model);
  758. });
  759. test("null and undefined are invalid ids.", 2, function() {
  760. var model = new Backbone.Model({id: 1});
  761. var collection = new Backbone.Collection([model]);
  762. model.set({id: null});
  763. ok(!collection.get('null'));
  764. model.set({id: 1});
  765. model.set({id: undefined});
  766. ok(!collection.get('undefined'));
  767. });
  768. test("falsy comparator", 4, function(){
  769. var Col = Backbone.Collection.extend({
  770. comparator: function(model){ return model.id; }
  771. });
  772. var col = new Col();
  773. var colFalse = new Col(null, {comparator: false});
  774. var colNull = new Col(null, {comparator: null});
  775. var colUndefined = new Col(null, {comparator: undefined});
  776. ok(col.comparator);
  777. ok(!colFalse.comparator);
  778. ok(!colNull.comparator);
  779. ok(colUndefined.comparator);
  780. });
  781. test("#1355 - `options` is passed to success callbacks", 2, function(){
  782. var m = new Backbone.Model({x:1});
  783. var col = new Backbone.Collection();
  784. var opts = {
  785. opts: true,
  786. success: function(collection, resp, options) {
  787. ok(options.opts);
  788. }
  789. };
  790. col.sync = m.sync = function( method, collection, options ){
  791. options.success({});
  792. };
  793. col.fetch(opts);
  794. col.create(m, opts);
  795. });
  796. test("#1412 - Trigger 'request' and 'sync' events.", 4, function() {
  797. var collection = new Backbone.Collection;
  798. collection.url = '/test';
  799. Backbone.ajax = function(settings){ settings.success(); };
  800. collection.on('request', function(obj, xhr, options) {
  801. ok(obj === collection, "collection has correct 'request' event after fetching");
  802. });
  803. collection.on('sync', function(obj, response, options) {
  804. ok(obj === collection, "collection has correct 'sync' event after fetching");
  805. });
  806. collection.fetch();
  807. collection.off();
  808. collection.on('request', function(obj, xhr, options) {
  809. ok(obj === collection.get(1), "collection has correct 'request' event after one of its models save");
  810. });
  811. collection.on('sync', function(obj, response, options) {
  812. ok(obj === collection.get(1), "collection has correct 'sync' event after one of its models save");
  813. });
  814. collection.create({id: 1});
  815. collection.off();
  816. });
  817. test("#3283 - fetch, create calls success with context", 2, function() {
  818. var collection = new Backbone.Collection;
  819. collection.url = '/test';
  820. Backbone.ajax = function(settings) {
  821. settings.success.call(settings.context);
  822. };
  823. var obj = {};
  824. var options = {
  825. context: obj,
  826. success: function() {
  827. equal(this, obj);
  828. }
  829. };
  830. collection.fetch(options);
  831. collection.create({id: 1}, options);
  832. });
  833. test("#1447 - create with wait adds model.", 1, function() {
  834. var collection = new Backbone.Collection;
  835. var model = new Backbone.Model;
  836. model.sync = function(method, model, options){ options.success(); };
  837. collection.on('add', function(){ ok(true); });
  838. collection.create(model, {wait: true});
  839. });
  840. test("#1448 - add sorts collection after merge.", 1, function() {
  841. var collection = new Backbone.Collection([
  842. {id: 1, x: 1},
  843. {id: 2, x: 2}
  844. ]);
  845. collection.comparator = function(model){ return model.get('x'); };
  846. collection.add({id: 1, x: 3}, {merge: true});
  847. deepEqual(collection.pluck('id'), [2, 1]);
  848. });
  849. test("#1655 - groupBy can be used with a string argument.", 3, function() {
  850. var collection = new Backbone.Collection([{x: 1}, {x: 2}]);
  851. var grouped = collection.groupBy('x');
  852. strictEqual(_.keys(grouped).length, 2);
  853. strictEqual(grouped[1][0].get('x'), 1);
  854. strictEqual(grouped[2][0].get('x'), 2);
  855. });
  856. test("#1655 - sortBy can be used with a string argument.", 1, function() {
  857. var collection = new Backbone.Collection([{x: 3}, {x: 1}, {x: 2}]);
  858. var values = _.map(collection.sortBy('x'), function(model) {
  859. return model.get('x');
  860. });
  861. deepEqual(values, [1, 2, 3]);
  862. });
  863. test("#1604 - Removal during iteration.", 0, function() {
  864. var collection = new Backbone.Collection([{}, {}]);
  865. collection.on('add', function() {
  866. collection.at(0).destroy();
  867. });
  868. collection.add({}, {at: 0});
  869. });
  870. test("#1638 - `sort` during `add` triggers correctly.", function() {
  871. var collection = new Backbone.Collection;
  872. collection.comparator = function(model) { return model.get('x'); };
  873. var added = [];
  874. collection.on('add', function(model) {
  875. model.set({x: 3});
  876. collection.sort();
  877. added.push(model.id);
  878. });
  879. collection.add([{id: 1, x: 1}, {id: 2, x: 2}]);
  880. deepEqual(added, [1, 2]);
  881. });
  882. test("fetch parses models by default", 1, function() {
  883. var model = {};
  884. var Collection = Backbone.Collection.extend({
  885. url: 'test',
  886. model: Backbone.Model.extend({
  887. parse: function(resp) {
  888. strictEqual(resp, model);
  889. }
  890. })
  891. });
  892. new Collection().fetch();
  893. this.ajaxSettings.success([model]);
  894. });
  895. test("`sort` shouldn't always fire on `add`", 1, function() {
  896. var c = new Backbone.Collection([{id: 1}, {id: 2}, {id: 3}], {
  897. comparator: 'id'
  898. });
  899. c.sort = function(){ ok(true); };
  900. c.add([]);
  901. c.add({id: 1});
  902. c.add([{id: 2}, {id: 3}]);
  903. c.add({id: 4});
  904. });
  905. test("#1407 parse option on constructor parses collection and models", 2, function() {
  906. var model = {
  907. namespace : [{id: 1}, {id:2}]
  908. };
  909. var Collection = Backbone.Collection.extend({
  910. model: Backbone.Model.extend({
  911. parse: function(model) {
  912. model.name = 'test';
  913. return model;
  914. }
  915. }),
  916. parse: function(model) {
  917. return model.namespace;
  918. }
  919. });
  920. var c = new Collection(model, {parse:true});
  921. equal(c.length, 2);
  922. equal(c.at(0).get('name'), 'test');
  923. });
  924. test("#1407 parse option on reset parses collection and models", 2, function() {
  925. var model = {
  926. namespace : [{id: 1}, {id:2}]
  927. };
  928. var Collection = Backbone.Collection.extend({
  929. model: Backbone.Model.extend({
  930. parse: function(model) {
  931. model.name = 'test';
  932. return model;
  933. }
  934. }),
  935. parse: function(model) {
  936. return model.namespace;
  937. }
  938. });
  939. var c = new Collection();
  940. c.reset(model, {parse:true});
  941. equal(c.length, 2);
  942. equal(c.at(0).get('name'), 'test');
  943. });
  944. test("Reset includes previous models in triggered event.", 1, function() {
  945. var model = new Backbone.Model();
  946. var collection = new Backbone.Collection([model])
  947. .on('reset', function(collection, options) {
  948. deepEqual(options.previousModels, [model]);
  949. });
  950. collection.reset([]);
  951. });
  952. test("set", function() {
  953. var m1 = new Backbone.Model();
  954. var m2 = new Backbone.Model({id: 2});
  955. var m3 = new Backbone.Model();
  956. var c = new Backbone.Collection([m1, m2]);
  957. // Test add/change/remove events
  958. c.on('add', function(model) {
  959. strictEqual(model, m3);
  960. });
  961. c.on('change', function(model) {
  962. strictEqual(model, m2);
  963. });
  964. c.on('remove', function(model) {
  965. strictEqual(model, m1);
  966. });
  967. // remove: false doesn't remove any models
  968. c.set([], {remove: false});
  969. strictEqual(c.length, 2);
  970. // add: false doesn't add any models
  971. c.set([m1, m2, m3], {add: false});
  972. strictEqual(c.length, 2);
  973. // merge: false doesn't change any models
  974. c.set([m1, {id: 2, a: 1}], {merge: false});
  975. strictEqual(m2.get('a'), void 0);
  976. // add: false, remove: false only merges existing models
  977. c.set([m1, {id: 2, a: 0}, m3, {id: 4}], {add: false, remove: false});
  978. strictEqual(c.length, 2);
  979. strictEqual(m2.get('a'), 0);
  980. // default options add/remove/merge as appropriate
  981. c.set([{id: 2, a: 1}, m3]);
  982. strictEqual(c.length, 2);
  983. strictEqual(m2.get('a'), 1);
  984. // Test removing models not passing an argument
  985. c.off('remove').on('remove', function(model) {
  986. ok(model === m2 || model === m3);
  987. });
  988. c.set([]);
  989. strictEqual(c.length, 0);
  990. });
  991. test("set with only cids", 3, function() {
  992. var m1 = new Backbone.Model;
  993. var m2 = new Backbone.Model;
  994. var c = new Backbone.Collection;
  995. c.set([m1, m2]);
  996. equal(c.length, 2);
  997. c.set([m1]);
  998. equal(c.length, 1);
  999. c.set([m1, m1, m1, m2, m2], {remove: false});
  1000. equal(c.length, 2);
  1001. });
  1002. test("set with only idAttribute", 3, function() {
  1003. var m1 = { _id: 1 };
  1004. var m2 = { _id: 2 };
  1005. var col = Backbone.Collection.extend({
  1006. model: Backbone.Model.extend({
  1007. idAttribute: '_id'
  1008. })
  1009. });
  1010. var c = new col;
  1011. c.set([m1, m2]);
  1012. equal(c.length, 2);
  1013. c.set([m1]);
  1014. equal(c.length, 1);
  1015. c.set([m1, m1, m1, m2, m2], {remove: false});
  1016. equal(c.length, 2);
  1017. });
  1018. test("set + merge with default values defined", function() {
  1019. var Model = Backbone.Model.extend({
  1020. defaults: {
  1021. key: 'value'
  1022. }
  1023. });
  1024. var m = new Model({id: 1});
  1025. var col = new Backbone.Collection([m], {model: Model});
  1026. equal(col.first().get('key'), 'value');
  1027. col.set({id: 1, key: 'other'});
  1028. equal(col.first().get('key'), 'other');
  1029. col.set({id: 1, other: 'value'});
  1030. equal(col.first().get('key'), 'other');
  1031. equal(col.length, 1);
  1032. });
  1033. test('merge without mutation', function () {
  1034. var Model = Backbone.Model.extend({
  1035. initialize: function (attrs, options) {
  1036. if (attrs.child) {
  1037. this.set('child', new Model(attrs.child, options), options);
  1038. }
  1039. }
  1040. });
  1041. var Collection = Backbone.Collection.extend({model: Model});
  1042. var data = [{id: 1, child: {id: 2}}];
  1043. var collection = new Collection(data);
  1044. equal(collection.first().id, 1);
  1045. collection.set(data);
  1046. equal(collection.first().id, 1);
  1047. collection.set([{id: 2, child: {id: 2}}].concat(data));
  1048. deepEqual(collection.pluck('id'), [2, 1]);
  1049. });
  1050. test("`set` and model level `parse`", function() {
  1051. var Model = Backbone.Model.extend({});
  1052. var Collection = Backbone.Collection.extend({
  1053. model: Model,
  1054. parse: function (res) { return _.pluck(res.models, 'model'); }
  1055. });
  1056. var model = new Model({id: 1});
  1057. var collection = new Collection(model);
  1058. collection.set({models: [
  1059. {model: {id: 1}},
  1060. {model: {id: 2}}
  1061. ]}, {parse: true});
  1062. equal(collection.first(), model);
  1063. });
  1064. test("`set` data is only parsed once", function() {
  1065. var collection = new Backbone.Collection();
  1066. collection.model = Backbone.Model.extend({
  1067. parse: function (data) {
  1068. equal(data.parsed, void 0);
  1069. data.parsed = true;
  1070. return data;
  1071. }
  1072. });
  1073. collection.set({}, {parse: true});
  1074. });
  1075. test('`set` matches input order in the absence of a comparator', function () {
  1076. var one = new Backbone.Model({id: 1});
  1077. var two = new Backbone.Model({id: 2});
  1078. var three = new Backbone.Model({id: 3});
  1079. var collection = new Backbone.Collection([one, two, three]);
  1080. collection.set([{id: 3}, {id: 2}, {id: 1}]);
  1081. deepEqual(collection.models, [three, two, one]);
  1082. collection.set([{id: 1}, {id: 2}]);
  1083. deepEqual(collection.models, [one, two]);
  1084. collection.set([two, three, one]);
  1085. deepEqual(collection.models, [two, three, one]);
  1086. collection.set([{id: 1}, {id: 2}], {remove: false});
  1087. deepEqual(collection.models, [two, three, one]);
  1088. collection.set([{id: 1}, {id: 2}, {id: 3}], {merge: false});
  1089. deepEqual(collection.models, [one, two, three]);
  1090. collection.set([three, two, one, {id: 4}], {add: false});
  1091. deepEqual(collection.models, [one, two, three]);
  1092. });
  1093. test("#1894 - Push should not trigger a sort", 0, function() {
  1094. var Collection = Backbone.Collection.extend({
  1095. comparator: 'id',
  1096. sort: function() { ok(false); }
  1097. });
  1098. new Collection().push({id: 1});
  1099. });
  1100. test("#2428 - push duplicate models, return the correct one", 1, function() {
  1101. var col = new Backbone.Collection;
  1102. var model1 = col.push({id: 101});
  1103. var model2 = col.push({id: 101})
  1104. ok(model2.cid == model1.cid);
  1105. });
  1106. test("`set` with non-normal id", function() {
  1107. var Collection = Backbone.Collection.extend({
  1108. model: Backbone.Model.extend({idAttribute: '_id'})
  1109. });
  1110. var collection = new Collection({_id: 1});
  1111. collection.set([{_id: 1, a: 1}], {add: false});
  1112. equal(collection.first().get('a'), 1);
  1113. });
  1114. test("#1894 - `sort` can optionally be turned off", 0, function() {
  1115. var Collection = Backbone.Collection.extend({
  1116. comparator: 'id',
  1117. sort: function() { ok(false); }
  1118. });
  1119. new Collection().add({id: 1}, {sort: false});
  1120. });
  1121. test("#1915 - `parse` data in the right order in `set`", function() {
  1122. var collection = new (Backbone.Collection.extend({
  1123. parse: function (data) {
  1124. strictEqual(data.status, 'ok');
  1125. return data.data;
  1126. }
  1127. }));
  1128. var res = {status: 'ok', data:[{id: 1}]};
  1129. collection.set(res, {parse: true});
  1130. });
  1131. asyncTest("#1939 - `parse` is passed `options`", 1, function () {
  1132. var collection = new (Backbone.Collection.extend({
  1133. url: '/',
  1134. parse: function (data, options) {
  1135. strictEqual(options.xhr.someHeader, 'headerValue');
  1136. return data;
  1137. }
  1138. }));
  1139. var ajax = Backbone.ajax;
  1140. Backbone.ajax = function (params) {
  1141. _.defer(params.success);
  1142. return {someHeader: 'headerValue'};
  1143. };
  1144. collection.fetch({
  1145. success: function () { start(); }
  1146. });
  1147. Backbone.ajax = ajax;
  1148. });
  1149. test("fetch will pass extra options to success callback", 1, function () {
  1150. var SpecialSyncCollection = Backbone.Collection.extend({
  1151. url: '/test',
  1152. sync: function (method, collection, options) {
  1153. _.extend(options, { specialSync: true });
  1154. return Backbone.Collection.prototype.sync.call(this, method, collection, options);
  1155. }
  1156. });
  1157. var collection = new SpecialSyncCollection();
  1158. var onSuccess = function (collection, resp, options) {
  1159. ok(options.specialSync, "Options were passed correctly to callback");
  1160. };
  1161. collection.fetch({ success: onSuccess });
  1162. this.ajaxSettings.success();
  1163. });
  1164. test("`add` only `sort`s when necessary", 2, function () {
  1165. var collection = new (Backbone.Collection.extend({
  1166. comparator: 'a'
  1167. }))([{id: 1}, {id: 2}, {id: 3}]);
  1168. collection.on('sort', function () { ok(true); });
  1169. collection.add({id: 4}); // do sort, new model
  1170. collection.add({id: 1, a: 1}, {merge: true}); // do sort, comparator change
  1171. collection.add({id: 1, b: 1}, {merge: true}); // don't sort, no comparator change
  1172. collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no comparator change
  1173. collection.add(collection.models); // don't sort, nothing new
  1174. collection.add(collection.models, {merge: true}); // don't sort
  1175. });
  1176. test("`add` only `sort`s when necessary with comparator function", 3, function () {
  1177. var collection = new (Backbone.Collection.extend({
  1178. comparator: function(a, b) {
  1179. return a.get('a') > b.get('a') ? 1 : (a.get('a') < b.get('a') ? -1 : 0);
  1180. }
  1181. }))([{id: 1}, {id: 2}, {id: 3}]);
  1182. collection.on('sort', function () { ok(true); });
  1183. collection.add({id: 4}); // do sort, new model
  1184. collection.add({id: 1, a: 1}, {merge: true}); // do sort, model change
  1185. collection.add({id: 1, b: 1}, {merge: true}); // do sort, model change
  1186. collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no model change
  1187. collection.add(collection.models); // don't sort, nothing new
  1188. collection.add(collection.models, {merge: true}); // don't sort
  1189. });
  1190. test("Attach options to collection.", 2, function() {
  1191. var Model = Backbone.Model;
  1192. var comparator = function(){};
  1193. var collection = new Backbone.Collection([], {
  1194. model: Model,
  1195. comparator: comparator
  1196. });
  1197. ok(collection.model === Model);
  1198. ok(collection.comparator === comparator);
  1199. });
  1200. test("`add` overrides `set` flags", function () {
  1201. var collection = new Backbone.Collection();
  1202. collection.once('add', function (model, collection, options) {
  1203. collection.add({id: 2}, options);
  1204. });
  1205. collection.set({id: 1});
  1206. equal(collection.length, 2);
  1207. });
  1208. test("#2606 - Collection#create, success arguments", 1, function() {
  1209. var collection = new Backbone.Collection;
  1210. collection.url = 'test';
  1211. collection.create({}, {
  1212. success: function(model, resp, options) {
  1213. strictEqual(resp, 'response');
  1214. }
  1215. });
  1216. this.ajaxSettings.success('response');
  1217. });
  1218. test("#2612 - nested `parse` works with `Collection#set`", function() {
  1219. var Job = Backbone.Model.extend({
  1220. constructor: function() {
  1221. this.items = new Items();
  1222. Backbone.Model.apply(this, arguments);
  1223. },
  1224. parse: function(attrs) {
  1225. this.items.set(attrs.items, {parse: true});
  1226. return _.omit(attrs, 'items');
  1227. }
  1228. });
  1229. var Item = Backbone.Model.extend({
  1230. constructor: function() {
  1231. this.subItems = new Backbone.Collection();
  1232. Backbone.Model.apply(this, arguments);
  1233. },
  1234. parse: function(attrs) {
  1235. this.subItems.set(attrs.subItems, {parse: true});
  1236. return _.omit(attrs, 'subItems');
  1237. }
  1238. });
  1239. var Items = Backbone.Collection.extend({
  1240. model: Item
  1241. });
  1242. var data = {
  1243. name: 'JobName',
  1244. id: 1,
  1245. items: [{
  1246. id: 1,
  1247. name: 'Sub1',
  1248. subItems: [
  1249. {id: 1, subName: 'One'},
  1250. {id: 2, subName: 'Two'}
  1251. ]
  1252. }, {
  1253. id: 2,
  1254. name: 'Sub2',
  1255. subItems: [
  1256. {id: 3, subName: 'Three'},
  1257. {id: 4, subName: 'Four'}
  1258. ]
  1259. }]
  1260. };
  1261. var newData = {
  1262. name: 'NewJobName',
  1263. id: 1,
  1264. items: [{
  1265. id: 1,
  1266. name: 'NewSub1',
  1267. subItems: [
  1268. {id: 1,subName: 'NewOne'},
  1269. {id: 2,subName: 'NewTwo'}
  1270. ]
  1271. }, {
  1272. id: 2,
  1273. name: 'NewSub2',
  1274. subItems: [
  1275. {id: 3,subName: 'NewThree'},
  1276. {id: 4,subName: 'NewFour'}
  1277. ]
  1278. }]
  1279. };
  1280. var job = new Job(data, {parse: true});
  1281. equal(job.get('name'), 'JobName');
  1282. equal(job.items.at(0).get('name'), 'Sub1');
  1283. equal(job.items.length, 2);
  1284. equal(job.items.get(1).subItems.get(1).get('subName'), 'One');
  1285. equal(job.items.get(2).subItems.get(3).get('subName'), 'Three');
  1286. job.set(job.parse(newData, {parse: true}));
  1287. equal(job.get('name'), 'NewJobName');
  1288. equal(job.items.at(0).get('name'), 'NewSub1');
  1289. equal(job.items.length, 2);
  1290. equal(job.items.get(1).subItems.get(1).get('subName'), 'NewOne');
  1291. equal(job.items.get(2).subItems.get(3).get('subName'), 'NewThree');
  1292. });
  1293. test('_addReference binds all collection events & adds to the lookup hashes', 9, function() {
  1294. var calls = {add: 0, remove: 0};
  1295. var Collection = Backbone.Collection.extend({
  1296. _addReference: function(model) {
  1297. Backbone.Collection.prototype._addReference.apply(this, arguments);
  1298. calls.add++;
  1299. equal(model, this._byId[model.id]);
  1300. equal(model, this._byId[model.cid]);
  1301. equal(model._events.all.length, 1);
  1302. },
  1303. _removeReference: function(model) {
  1304. Backbone.Collection.prototype._removeReference.apply(this, arguments);
  1305. calls.remove++;
  1306. equal(this._byId[model.id], void 0);
  1307. equal(this._byId[model.cid], void 0);
  1308. equal(model.collection, void 0);
  1309. equal(model._events, void 0);
  1310. }
  1311. });
  1312. var collection = new Collection();
  1313. var model = collection.add({id: 1});
  1314. collection.remove(model);
  1315. equal(calls.add, 1);
  1316. equal(calls.remove, 1);
  1317. });
  1318. test('Do not allow duplicate models to be `add`ed or `set`', function() {
  1319. var c = new Backbone.Collection();
  1320. c.add([{id: 1}, {id: 1}]);
  1321. equal(c.length, 1);
  1322. equal(c.models.length, 1);
  1323. c.set([{id: 1}, {id: 1}]);
  1324. equal(c.length, 1);
  1325. equal(c.models.length, 1);
  1326. });
  1327. test('#3020: #set with {add: false} should not throw.', 2, function() {
  1328. var collection = new Backbone.Collection;
  1329. collection.set([{id: 1}], {add: false});
  1330. strictEqual(collection.length, 0);
  1331. strictEqual(collection.models.length, 0);
  1332. });
  1333. test("create with wait, model instance, #3028", 1, function() {
  1334. var collection = new Backbone.Collection();
  1335. var model = new Backbone.Model({id: 1});
  1336. model.sync = function(){
  1337. equal(this.collection, collection);
  1338. };
  1339. collection.create(model, {wait: true});
  1340. });
  1341. test("modelId", function() {
  1342. var Stooge = Backbone.Model.extend();
  1343. var StoogeCollection = Backbone.Collection.extend({model: Stooge});
  1344. // Default to using `Collection::model::idAttribute`.
  1345. equal(StoogeCollection.prototype.modelId({id: 1}), 1);
  1346. Stooge.prototype.idAttribute = '_id';
  1347. equal(StoogeCollection.prototype.modelId({_id: 1}), 1);
  1348. });
  1349. test('Polymorphic models work with "simple" constructors', function () {
  1350. var A = Backbone.Model.extend();
  1351. var B = Backbone.Model.extend();
  1352. var C = Backbone.Collection.extend({
  1353. model: function (attrs) {
  1354. return attrs.type === 'a' ? new A(attrs) : new B(attrs);
  1355. }
  1356. });
  1357. var collection = new C([{id: 1, type: 'a'}, {id: 2, type: 'b'}]);
  1358. equal(collection.length, 2);
  1359. ok(collection.at(0) instanceof A);
  1360. equal(collection.at(0).id, 1);
  1361. ok(collection.at(1) instanceof B);
  1362. equal(collection.at(1).id, 2);
  1363. });
  1364. test('Polymorphic models work with "advanced" constructors', function () {
  1365. var A = Backbone.Model.extend({idAttribute: '_id'});
  1366. var B = Backbone.Model.extend({idAttribute: '_id'});
  1367. var C = Backbone.Collection.extend({
  1368. model: Backbone.Model.extend({
  1369. constructor: function (attrs) {
  1370. return attrs.type === 'a' ? new A(attrs) : new B(attrs);
  1371. },
  1372. idAttribute: '_id'
  1373. })
  1374. });
  1375. var collection = new C([{_id: 1, type: 'a'}, {_id: 2, type: 'b'}]);
  1376. equal(collection.length, 2);
  1377. ok(collection.at(0) instanceof A);
  1378. equal(collection.at(0), collection.get(1));
  1379. ok(collection.at(1) instanceof B);
  1380. equal(collection.at(1), collection.get(2));
  1381. C = Backbone.Collection.extend({
  1382. model: function (attrs) {
  1383. return attrs.type === 'a' ? new A(attrs) : new B(attrs);
  1384. },
  1385. modelId: function (attrs) {
  1386. return attrs.type + '-' + attrs.id;
  1387. }
  1388. });
  1389. collection = new C([{id: 1, type: 'a'}, {id: 1, type: 'b'}]);
  1390. equal(collection.length, 2);
  1391. ok(collection.at(0) instanceof A);
  1392. equal(collection.at(0), collection.get('a-1'));
  1393. ok(collection.at(1) instanceof B);
  1394. equal(collection.at(1), collection.get('b-1'));
  1395. });
  1396. test("#3039: adding at index fires with correct at", 3, function() {
  1397. var col = new Backbone.Collection([{at: 0}, {at: 4}]);
  1398. col.on('add', function(model, col, options) {
  1399. equal(model.get('at'), options.index);
  1400. });
  1401. col.add([{at: 1}, {at: 2}, {at: 3}], {at: 1});
  1402. });
  1403. test("#3039: index is not sent when at is not specified", 2, function() {
  1404. var col = new Backbone.Collection([{at: 0}]);
  1405. col.on('add', function(model, col, options) {
  1406. equal(undefined, options.index);
  1407. });
  1408. col.add([{at: 1}, {at: 2}]);
  1409. });
  1410. test('#3199 - Order changing should trigger a sort', 1, function() {
  1411. var one = new Backbone.Model({id: 1});
  1412. var two = new Backbone.Model({id: 2});
  1413. var three = new Backbone.Model({id: 3});
  1414. var collection = new Backbone.Collection([one, two, three]);
  1415. collection.on('sort', function() {
  1416. ok(true);
  1417. });
  1418. collection.set([{id: 3}, {id: 2}, {id: 1}]);
  1419. });
  1420. test('#3199 - Adding a model should trigger a sort', 1, function() {
  1421. var one = new Backbone.Model({id: 1});
  1422. var two = new Backbone.Model({id: 2});
  1423. var three = new Backbone.Model({id: 3});
  1424. var collection = new Backbone.Collection([one, two, three]);
  1425. collection.on('sort', function() {
  1426. ok(true);
  1427. });
  1428. collection.set([{id: 3}, {id: 2}, {id: 1}, {id: 0}]);
  1429. })
  1430. test('#3199 - Order not changing should not trigger a sort', 0, function() {
  1431. var one = new Backbone.Model({id: 1});
  1432. var two = new Backbone.Model({id: 2});
  1433. var three = new Backbone.Model({id: 3});
  1434. var collection = new Backbone.Collection([one, two, three]);
  1435. collection.on('sort', function() {
  1436. ok(false);
  1437. });
  1438. collection.set([{id: 1}, {id: 2}, {id: 3}]);
  1439. });
  1440. test("add supports negative indexes", 1, function() {
  1441. var collection = new Backbone.Collection([{id: 1}]);
  1442. collection.add([{id: 2}, {id: 3}], {at: -1});
  1443. collection.add([{id: 2.5}], {at: -2});
  1444. equal(collection.pluck('id').join(','), "1,2,2.5,3");
  1445. });
  1446. test("#set accepts options.at as a string", 1, function() {
  1447. var collection = new Backbone.Collection([{id: 1}, {id: 2}]);
  1448. collection.add([{id: 3}], {at: '1'});
  1449. deepEqual(collection.pluck('id'), [1, 3, 2]);
  1450. });
  1451. test("adding multiple models triggers `set` event once", 1, function() {
  1452. var collection = new Backbone.Collection;
  1453. collection.on('update', function() { ok(true); });
  1454. collection.add([{id: 1}, {id: 2}, {id: 3}]);
  1455. });
  1456. test("removing models triggers `set` event once", 1, function() {
  1457. var collection = new Backbone.Collection([{id: 1}, {id: 2}, {id: 3}]);
  1458. collection.on('update', function() { ok(true); });
  1459. collection.remove([{id: 1}, {id: 2}]);
  1460. });
  1461. test("remove does not trigger `set` when nothing removed", 0, function() {
  1462. var collection = new Backbone.Collection([{id: 1}, {id: 2}]);
  1463. collection.on('update', function() { ok(false); });
  1464. collection.remove([{id: 3}]);
  1465. });
  1466. test("set triggers `set` event once", 1, function() {
  1467. var collection = new Backbone.Collection([{id: 1}, {id: 2}]);
  1468. collection.on('update', function() { ok(true); });
  1469. collection.set([{id: 1}, {id: 3}]);
  1470. });
  1471. test("set does not trigger `set` event when nothing added nor removed", 0, function() {
  1472. var collection = new Backbone.Collection([{id: 1}, {id: 2}]);
  1473. collection.on('update', function() { ok(false); });
  1474. collection.set([{id: 1}, {id: 2}]);
  1475. });
  1476. test("#3610 - invoke collects arguments", 3, function() {
  1477. var Model = Backbone.Model.extend({
  1478. method: function(a, b, c) {
  1479. equal(a, 1);
  1480. equal(b, 2);
  1481. equal(c, 3);
  1482. }
  1483. });
  1484. var Collection = Backbone.Collection.extend({
  1485. model: Model
  1486. });
  1487. var collection = new Collection([{id: 1}]);
  1488. collection.invoke('method', 1, 2, 3);
  1489. });
  1490. })();