PageRenderTime 54ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/test/collection.js

https://github.com/huangbaihua001/backbone
JavaScript | 1154 lines | 1033 code | 114 blank | 7 comment | 11 complexity | 18105cb45a633bfd19b1d2aa810135c8 MD5 | raw file
  1. $(document).ready(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", 9, function() {
  15. var counter = 0;
  16. col.on('sort', function(){ counter++; });
  17. equal(col.first(), a, "a should be first");
  18. equal(col.last(), d, "d should be last");
  19. col.comparator = function(a, b) {
  20. return a.id > b.id ? -1 : 1;
  21. };
  22. col.sort();
  23. equal(counter, 1);
  24. equal(col.first(), a, "a should be first");
  25. equal(col.last(), d, "d should be last");
  26. col.comparator = function(model) { return model.id; };
  27. col.sort();
  28. equal(counter, 2);
  29. equal(col.first(), d, "d should be first");
  30. equal(col.last(), a, "a should be last");
  31. equal(col.length, 4);
  32. });
  33. test("String comparator.", 1, function() {
  34. var collection = new Backbone.Collection([
  35. {id: 3},
  36. {id: 1},
  37. {id: 2}
  38. ], {comparator: 'id'});
  39. deepEqual(collection.pluck('id'), [1, 2, 3]);
  40. });
  41. test("new and parse", 3, function() {
  42. var Collection = Backbone.Collection.extend({
  43. parse : function(data) {
  44. return _.filter(data, function(datum) {
  45. return datum.a % 2 === 0;
  46. });
  47. }
  48. });
  49. var models = [{a: 1}, {a: 2}, {a: 3}, {a: 4}];
  50. var collection = new Collection(models, {parse: true});
  51. strictEqual(collection.length, 2);
  52. strictEqual(collection.first().get('a'), 2);
  53. strictEqual(collection.last().get('a'), 4);
  54. });
  55. test("get", 6, function() {
  56. equal(col.get(0), d);
  57. equal(col.get(d.clone()), d);
  58. equal(col.get(2), b);
  59. equal(col.get({id: 1}), c);
  60. equal(col.get(c.clone()), c);
  61. equal(col.get(col.first().cid), col.first());
  62. });
  63. test("get with non-default ids", 5, function() {
  64. var col = new Backbone.Collection();
  65. var MongoModel = Backbone.Model.extend({idAttribute: '_id'});
  66. var model = new MongoModel({_id: 100});
  67. col.add(model);
  68. equal(col.get(100), model);
  69. equal(col.get(model.cid), model);
  70. equal(col.get(model), model);
  71. equal(col.get(101), void 0);
  72. var col2 = new Backbone.Collection();
  73. col2.model = MongoModel;
  74. col2.add(model.attributes);
  75. equal(col2.get(model.clone()), col2.first());
  76. });
  77. test("update index when id changes", 4, function() {
  78. var col = new Backbone.Collection();
  79. col.add([
  80. {id : 0, name : 'one'},
  81. {id : 1, name : 'two'}
  82. ]);
  83. var one = col.get(0);
  84. equal(one.get('name'), 'one');
  85. col.on('change:name', function (model) { ok(this.get(model)); });
  86. one.set({name: 'dalmatians', id : 101});
  87. equal(col.get(0), null);
  88. equal(col.get(101).get('name'), 'dalmatians');
  89. });
  90. test("at", 1, function() {
  91. equal(col.at(2), c);
  92. });
  93. test("pluck", 1, function() {
  94. equal(col.pluck('label').join(' '), 'a b c d');
  95. });
  96. test("add", 10, function() {
  97. var added, opts, secondAdded;
  98. added = opts = secondAdded = null;
  99. e = new Backbone.Model({id: 10, label : 'e'});
  100. otherCol.add(e);
  101. otherCol.on('add', function() {
  102. secondAdded = true;
  103. });
  104. col.on('add', function(model, collection, options){
  105. added = model.get('label');
  106. opts = options;
  107. });
  108. col.add(e, {amazing: true});
  109. equal(added, 'e');
  110. equal(col.length, 5);
  111. equal(col.last(), e);
  112. equal(otherCol.length, 1);
  113. equal(secondAdded, null);
  114. ok(opts.amazing);
  115. var f = new Backbone.Model({id: 20, label : 'f'});
  116. var g = new Backbone.Model({id: 21, label : 'g'});
  117. var h = new Backbone.Model({id: 22, label : 'h'});
  118. var atCol = new Backbone.Collection([f, g, h]);
  119. equal(atCol.length, 3);
  120. atCol.add(e, {at: 1});
  121. equal(atCol.length, 4);
  122. equal(atCol.at(1), e);
  123. equal(atCol.last(), h);
  124. });
  125. test("add multiple models", 6, function() {
  126. var col = new Backbone.Collection([{at: 0}, {at: 1}, {at: 9}]);
  127. col.add([{at: 2}, {at: 3}, {at: 4}, {at: 5}, {at: 6}, {at: 7}, {at: 8}], {at: 2});
  128. for (var i = 0; i <= 5; i++) {
  129. equal(col.at(i).get('at'), i);
  130. }
  131. });
  132. test("add; at should have preference over comparator", 1, function() {
  133. var Col = Backbone.Collection.extend({
  134. comparator: function(a,b) {
  135. return a.id > b.id ? -1 : 1;
  136. }
  137. });
  138. var col = new Col([{id: 2}, {id: 3}]);
  139. col.add(new Backbone.Model({id: 1}), {at: 1});
  140. equal(col.pluck('id').join(' '), '3 1 2');
  141. });
  142. test("can't add model to collection twice", function() {
  143. var col = new Backbone.Collection([{id: 1}, {id: 2}, {id: 1}, {id: 2}, {id: 3}]);
  144. equal(col.pluck('id').join(' '), '1 2 3');
  145. });
  146. test("can't add different model with same id to collection twice", 1, function() {
  147. var col = new Backbone.Collection;
  148. col.unshift({id: 101});
  149. col.add({id: 101});
  150. equal(col.length, 1);
  151. });
  152. test("merge in duplicate models with {merge: true}", 3, function() {
  153. var col = new Backbone.Collection;
  154. col.add([{id: 1, name: 'Moe'}, {id: 2, name: 'Curly'}, {id: 3, name: 'Larry'}]);
  155. col.add({id: 1, name: 'Moses'});
  156. equal(col.first().get('name'), 'Moe');
  157. col.add({id: 1, name: 'Moses'}, {merge: true});
  158. equal(col.first().get('name'), 'Moses');
  159. col.add({id: 1, name: 'Tim'}, {merge: true, silent: true});
  160. equal(col.first().get('name'), 'Tim');
  161. });
  162. test("add model to multiple collections", 10, function() {
  163. var counter = 0;
  164. var e = new Backbone.Model({id: 10, label : 'e'});
  165. e.on('add', function(model, collection) {
  166. counter++;
  167. equal(e, model);
  168. if (counter > 1) {
  169. equal(collection, colF);
  170. } else {
  171. equal(collection, colE);
  172. }
  173. });
  174. var colE = new Backbone.Collection([]);
  175. colE.on('add', function(model, collection) {
  176. equal(e, model);
  177. equal(colE, collection);
  178. });
  179. var colF = new Backbone.Collection([]);
  180. colF.on('add', function(model, collection) {
  181. equal(e, model);
  182. equal(colF, collection);
  183. });
  184. colE.add(e);
  185. equal(e.collection, colE);
  186. colF.add(e);
  187. equal(e.collection, colE);
  188. });
  189. test("add model with parse", 1, function() {
  190. var Model = Backbone.Model.extend({
  191. parse: function(obj) {
  192. obj.value += 1;
  193. return obj;
  194. }
  195. });
  196. var Col = Backbone.Collection.extend({model: Model});
  197. var col = new Col;
  198. col.add({value: 1}, {parse: true});
  199. equal(col.at(0).get('value'), 2);
  200. });
  201. test("add with parse and merge", function() {
  202. var Model = Backbone.Model.extend({
  203. parse: function (data) {
  204. return data.model;
  205. }
  206. });
  207. var collection = new Backbone.Collection();
  208. collection.model = Model;
  209. collection.add({id: 1});
  210. collection.add({model: {id: 1, name: 'Alf'}}, {parse: true, merge: true});
  211. equal(collection.first().get('name'), 'Alf');
  212. });
  213. test("add model to collection with sort()-style comparator", 3, function() {
  214. var col = new Backbone.Collection;
  215. col.comparator = function(a, b) {
  216. return a.get('name') < b.get('name') ? -1 : 1;
  217. };
  218. var tom = new Backbone.Model({name: 'Tom'});
  219. var rob = new Backbone.Model({name: 'Rob'});
  220. var tim = new Backbone.Model({name: 'Tim'});
  221. col.add(tom);
  222. col.add(rob);
  223. col.add(tim);
  224. equal(col.indexOf(rob), 0);
  225. equal(col.indexOf(tim), 1);
  226. equal(col.indexOf(tom), 2);
  227. });
  228. test("comparator that depends on `this`", 2, function() {
  229. var col = new Backbone.Collection;
  230. col.negative = function(num) {
  231. return -num;
  232. };
  233. col.comparator = function(a) {
  234. return this.negative(a.id);
  235. };
  236. col.add([{id: 1}, {id: 2}, {id: 3}]);
  237. deepEqual(col.pluck('id'), [3, 2, 1]);
  238. col.comparator = function(a, b) {
  239. return this.negative(b.id) - this.negative(a.id);
  240. };
  241. col.sort();
  242. deepEqual(col.pluck('id'), [1, 2, 3]);
  243. });
  244. test("remove", 5, function() {
  245. var removed = null;
  246. var otherRemoved = null;
  247. col.on('remove', function(model, col, options) {
  248. removed = model.get('label');
  249. equal(options.index, 3);
  250. });
  251. otherCol.on('remove', function(model, col, options) {
  252. otherRemoved = true;
  253. });
  254. col.remove(d);
  255. equal(removed, 'd');
  256. equal(col.length, 3);
  257. equal(col.first(), a);
  258. equal(otherRemoved, null);
  259. });
  260. test("shift and pop", 2, function() {
  261. var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
  262. equal(col.shift().get('a'), 'a');
  263. equal(col.pop().get('c'), 'c');
  264. });
  265. test("slice", 2, function() {
  266. var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
  267. var array = col.slice(1, 3);
  268. equal(array.length, 2);
  269. equal(array[0].get('b'), 'b');
  270. });
  271. test("events are unbound on remove", 3, function() {
  272. var counter = 0;
  273. var dj = new Backbone.Model();
  274. var emcees = new Backbone.Collection([dj]);
  275. emcees.on('change', function(){ counter++; });
  276. dj.set({name : 'Kool'});
  277. equal(counter, 1);
  278. emcees.reset([]);
  279. equal(dj.collection, undefined);
  280. dj.set({name : 'Shadow'});
  281. equal(counter, 1);
  282. });
  283. test("remove in multiple collections", 7, function() {
  284. var modelData = {
  285. id : 5,
  286. title : 'Othello'
  287. };
  288. var passed = false;
  289. var e = new Backbone.Model(modelData);
  290. var f = new Backbone.Model(modelData);
  291. f.on('remove', function() {
  292. passed = true;
  293. });
  294. var colE = new Backbone.Collection([e]);
  295. var colF = new Backbone.Collection([f]);
  296. ok(e != f);
  297. ok(colE.length === 1);
  298. ok(colF.length === 1);
  299. colE.remove(e);
  300. equal(passed, false);
  301. ok(colE.length === 0);
  302. colF.remove(e);
  303. ok(colF.length === 0);
  304. equal(passed, true);
  305. });
  306. test("remove same model in multiple collection", 16, function() {
  307. var counter = 0;
  308. var e = new Backbone.Model({id: 5, title: 'Othello'});
  309. e.on('remove', function(model, collection) {
  310. counter++;
  311. equal(e, model);
  312. if (counter > 1) {
  313. equal(collection, colE);
  314. } else {
  315. equal(collection, colF);
  316. }
  317. });
  318. var colE = new Backbone.Collection([e]);
  319. colE.on('remove', function(model, collection) {
  320. equal(e, model);
  321. equal(colE, collection);
  322. });
  323. var colF = new Backbone.Collection([e]);
  324. colF.on('remove', function(model, collection) {
  325. equal(e, model);
  326. equal(colF, collection);
  327. });
  328. equal(colE, e.collection);
  329. colF.remove(e);
  330. ok(colF.length === 0);
  331. ok(colE.length === 1);
  332. equal(counter, 1);
  333. equal(colE, e.collection);
  334. colE.remove(e);
  335. equal(null, e.collection);
  336. ok(colE.length === 0);
  337. equal(counter, 2);
  338. });
  339. test("model destroy removes from all collections", 3, function() {
  340. var e = new Backbone.Model({id: 5, title: 'Othello'});
  341. e.sync = function(method, model, options) { options.success(); };
  342. var colE = new Backbone.Collection([e]);
  343. var colF = new Backbone.Collection([e]);
  344. e.destroy();
  345. ok(colE.length === 0);
  346. ok(colF.length === 0);
  347. equal(undefined, e.collection);
  348. });
  349. test("Colllection: non-persisted model destroy removes from all collections", 3, function() {
  350. var e = new Backbone.Model({title: 'Othello'});
  351. e.sync = function(method, model, options) { throw "should not be called"; };
  352. var colE = new Backbone.Collection([e]);
  353. var colF = new Backbone.Collection([e]);
  354. e.destroy();
  355. ok(colE.length === 0);
  356. ok(colF.length === 0);
  357. equal(undefined, e.collection);
  358. });
  359. test("fetch", 4, function() {
  360. var collection = new Backbone.Collection;
  361. collection.url = '/test';
  362. collection.fetch();
  363. equal(this.syncArgs.method, 'read');
  364. equal(this.syncArgs.model, collection);
  365. equal(this.syncArgs.options.parse, true);
  366. collection.fetch({parse: false});
  367. equal(this.syncArgs.options.parse, false);
  368. });
  369. test("fetch with an error response triggers an error event", 1, function () {
  370. var collection = new Backbone.Collection();
  371. collection.on('error', function () {
  372. ok(true);
  373. });
  374. collection.sync = function (method, model, options) { options.error(); };
  375. collection.fetch();
  376. });
  377. test("ensure fetch only parses once", 1, function() {
  378. var collection = new Backbone.Collection;
  379. var counter = 0;
  380. collection.parse = function(models) {
  381. counter++;
  382. return models;
  383. };
  384. collection.url = '/test';
  385. collection.fetch();
  386. this.syncArgs.options.success();
  387. equal(counter, 1);
  388. });
  389. test("create", 4, function() {
  390. var collection = new Backbone.Collection;
  391. collection.url = '/test';
  392. var model = collection.create({label: 'f'}, {wait: true});
  393. equal(this.syncArgs.method, 'create');
  394. equal(this.syncArgs.model, model);
  395. equal(model.get('label'), 'f');
  396. equal(model.collection, collection);
  397. });
  398. test("create with validate:true enforces validation", 2, function() {
  399. var ValidatingModel = Backbone.Model.extend({
  400. validate: function(attrs) {
  401. return "fail";
  402. }
  403. });
  404. var ValidatingCollection = Backbone.Collection.extend({
  405. model: ValidatingModel
  406. });
  407. var col = new ValidatingCollection();
  408. col.on('invalid', function (collection, attrs, options) {
  409. equal(options.validationError, 'fail');
  410. });
  411. equal(col.create({"foo":"bar"}, {validate:true}), false);
  412. });
  413. test("a failing create returns model with errors", function() {
  414. var ValidatingModel = Backbone.Model.extend({
  415. validate: function(attrs) {
  416. return "fail";
  417. }
  418. });
  419. var ValidatingCollection = Backbone.Collection.extend({
  420. model: ValidatingModel
  421. });
  422. var col = new ValidatingCollection();
  423. var m = col.create({"foo":"bar"});
  424. equal(m.validationError, 'fail');
  425. equal(col.length, 1);
  426. });
  427. test("initialize", 1, function() {
  428. var Collection = Backbone.Collection.extend({
  429. initialize: function() {
  430. this.one = 1;
  431. }
  432. });
  433. var coll = new Collection;
  434. equal(coll.one, 1);
  435. });
  436. test("toJSON", 1, function() {
  437. equal(JSON.stringify(col), '[{"id":3,"label":"a"},{"id":2,"label":"b"},{"id":1,"label":"c"},{"id":0,"label":"d"}]');
  438. });
  439. test("where and findWhere", 8, function() {
  440. var model = new Backbone.Model({a: 1});
  441. var coll = new Backbone.Collection([
  442. model,
  443. {a: 1},
  444. {a: 1, b: 2},
  445. {a: 2, b: 2},
  446. {a: 3}
  447. ]);
  448. equal(coll.where({a: 1}).length, 3);
  449. equal(coll.where({a: 2}).length, 1);
  450. equal(coll.where({a: 3}).length, 1);
  451. equal(coll.where({b: 1}).length, 0);
  452. equal(coll.where({b: 2}).length, 2);
  453. equal(coll.where({a: 1, b: 2}).length, 1);
  454. equal(coll.findWhere({a: 1}), model);
  455. equal(coll.findWhere({a: 4}), void 0);
  456. });
  457. test("Underscore methods", 14, function() {
  458. equal(col.map(function(model){ return model.get('label'); }).join(' '), 'a b c d');
  459. equal(col.any(function(model){ return model.id === 100; }), false);
  460. equal(col.any(function(model){ return model.id === 0; }), true);
  461. equal(col.indexOf(b), 1);
  462. equal(col.size(), 4);
  463. equal(col.rest().length, 3);
  464. ok(!_.include(col.rest(), a));
  465. ok(_.include(col.rest(), d));
  466. ok(!col.isEmpty());
  467. ok(!_.include(col.without(d), d));
  468. equal(col.max(function(model){ return model.id; }).id, 3);
  469. equal(col.min(function(model){ return model.id; }).id, 0);
  470. deepEqual(col.chain()
  471. .filter(function(o){ return o.id % 2 === 0; })
  472. .map(function(o){ return o.id * 2; })
  473. .value(),
  474. [4, 0]);
  475. deepEqual(col.difference([c, d]), [a, b]);
  476. });
  477. test("sortedIndex", function () {
  478. var model = new Backbone.Model({key: 2});
  479. var collection = new (Backbone.Collection.extend({
  480. comparator: 'key'
  481. }))([model, {key: 1}]);
  482. equal(collection.sortedIndex(model), 1);
  483. equal(collection.sortedIndex(model, 'key'), 1);
  484. equal(collection.sortedIndex(model, function (model) {
  485. return model.get('key');
  486. }), 1);
  487. });
  488. test("reset", 12, function() {
  489. var resetCount = 0;
  490. var models = col.models;
  491. col.on('reset', function() { resetCount += 1; });
  492. col.reset([]);
  493. equal(resetCount, 1);
  494. equal(col.length, 0);
  495. equal(col.last(), null);
  496. col.reset(models);
  497. equal(resetCount, 2);
  498. equal(col.length, 4);
  499. equal(col.last(), d);
  500. col.reset(_.map(models, function(m){ return m.attributes; }));
  501. equal(resetCount, 3);
  502. equal(col.length, 4);
  503. ok(col.last() !== d);
  504. ok(_.isEqual(col.last().attributes, d.attributes));
  505. col.reset();
  506. equal(col.length, 0);
  507. equal(resetCount, 4);
  508. });
  509. test ("reset with different values", function(){
  510. var col = new Backbone.Collection({id: 1});
  511. col.reset({id: 1, a: 1});
  512. equal(col.get(1).get('a'), 1);
  513. });
  514. test("same references in reset", function() {
  515. var model = new Backbone.Model({id: 1});
  516. var collection = new Backbone.Collection({id: 1});
  517. collection.reset(model);
  518. equal(collection.get(1), model);
  519. });
  520. test("reset passes caller options", 3, function() {
  521. var Model = Backbone.Model.extend({
  522. initialize: function(attrs, options) {
  523. this.model_parameter = options.model_parameter;
  524. }
  525. });
  526. var col = new (Backbone.Collection.extend({ model: Model }))();
  527. col.reset([{ astring: "green", anumber: 1 }, { astring: "blue", anumber: 2 }], { model_parameter: 'model parameter' });
  528. equal(col.length, 2);
  529. col.each(function(model) {
  530. equal(model.model_parameter, 'model parameter');
  531. });
  532. });
  533. test("trigger custom events on models", 1, function() {
  534. var fired = null;
  535. a.on("custom", function() { fired = true; });
  536. a.trigger("custom");
  537. equal(fired, true);
  538. });
  539. test("add does not alter arguments", 2, function(){
  540. var attrs = {};
  541. var models = [attrs];
  542. new Backbone.Collection().add(models);
  543. equal(models.length, 1);
  544. ok(attrs === models[0]);
  545. });
  546. test("#714: access `model.collection` in a brand new model.", 2, function() {
  547. var collection = new Backbone.Collection;
  548. collection.url = '/test';
  549. var Model = Backbone.Model.extend({
  550. set: function(attrs) {
  551. equal(attrs.prop, 'value');
  552. equal(this.collection, collection);
  553. return this;
  554. }
  555. });
  556. collection.model = Model;
  557. collection.create({prop: 'value'});
  558. });
  559. test("#574, remove its own reference to the .models array.", 2, function() {
  560. var col = new Backbone.Collection([
  561. {id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}
  562. ]);
  563. equal(col.length, 6);
  564. col.remove(col.models);
  565. equal(col.length, 0);
  566. });
  567. test("#861, adding models to a collection which do not pass validation, with validate:true", function() {
  568. var Model = Backbone.Model.extend({
  569. validate: function(attrs) {
  570. if (attrs.id == 3) return "id can't be 3";
  571. }
  572. });
  573. var Collection = Backbone.Collection.extend({
  574. model: Model
  575. });
  576. var collection = new Collection;
  577. collection.on("error", function() { ok(true); });
  578. collection.add([{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}], {validate:true});
  579. deepEqual(collection.pluck('id'), [1, 2, 4, 5, 6]);
  580. });
  581. test("Invalid models are discarded with validate:true.", 5, function() {
  582. var collection = new Backbone.Collection;
  583. collection.on('test', function() { ok(true); });
  584. collection.model = Backbone.Model.extend({
  585. validate: function(attrs){ if (!attrs.valid) return 'invalid'; }
  586. });
  587. var model = new collection.model({id: 1, valid: true});
  588. collection.add([model, {id: 2}], {validate:true});
  589. model.trigger('test');
  590. ok(collection.get(model.cid));
  591. ok(collection.get(1));
  592. ok(!collection.get(2));
  593. equal(collection.length, 1);
  594. });
  595. test("multiple copies of the same model", 3, function() {
  596. var col = new Backbone.Collection();
  597. var model = new Backbone.Model();
  598. col.add([model, model]);
  599. equal(col.length, 1);
  600. col.add([{id: 1}, {id: 1}]);
  601. equal(col.length, 2);
  602. equal(col.last().id, 1);
  603. });
  604. test("#964 - collection.get return inconsistent", 2, function() {
  605. var c = new Backbone.Collection();
  606. ok(c.get(null) === undefined);
  607. ok(c.get() === undefined);
  608. });
  609. test("#1112 - passing options.model sets collection.model", 2, function() {
  610. var Model = Backbone.Model.extend({});
  611. var c = new Backbone.Collection([{id: 1}], {model: Model});
  612. ok(c.model === Model);
  613. ok(c.at(0) instanceof Model);
  614. });
  615. test("null and undefined are invalid ids.", 2, function() {
  616. var model = new Backbone.Model({id: 1});
  617. var collection = new Backbone.Collection([model]);
  618. model.set({id: null});
  619. ok(!collection.get('null'));
  620. model.set({id: 1});
  621. model.set({id: undefined});
  622. ok(!collection.get('undefined'));
  623. });
  624. test("falsy comparator", 4, function(){
  625. var Col = Backbone.Collection.extend({
  626. comparator: function(model){ return model.id; }
  627. });
  628. var col = new Col();
  629. var colFalse = new Col(null, {comparator: false});
  630. var colNull = new Col(null, {comparator: null});
  631. var colUndefined = new Col(null, {comparator: undefined});
  632. ok(col.comparator);
  633. ok(!colFalse.comparator);
  634. ok(!colNull.comparator);
  635. ok(colUndefined.comparator);
  636. });
  637. test("#1355 - `options` is passed to success callbacks", 2, function(){
  638. var m = new Backbone.Model({x:1});
  639. var col = new Backbone.Collection();
  640. var opts = {
  641. success: function(collection, resp, options){
  642. ok(options);
  643. }
  644. };
  645. col.sync = m.sync = function( method, collection, options ){
  646. options.success(collection, [], options);
  647. };
  648. col.fetch(opts);
  649. col.create(m, opts);
  650. });
  651. test("#1412 - Trigger 'request' and 'sync' events.", 4, function() {
  652. var collection = new Backbone.Collection;
  653. collection.url = '/test';
  654. Backbone.ajax = function(settings){ settings.success(); };
  655. collection.on('request', function(obj, xhr, options) {
  656. ok(obj === collection, "collection has correct 'request' event after fetching");
  657. });
  658. collection.on('sync', function(obj, response, options) {
  659. ok(obj === collection, "collection has correct 'sync' event after fetching");
  660. });
  661. collection.fetch();
  662. collection.off();
  663. collection.on('request', function(obj, xhr, options) {
  664. ok(obj === collection.get(1), "collection has correct 'request' event after one of its models save");
  665. });
  666. collection.on('sync', function(obj, response, options) {
  667. ok(obj === collection.get(1), "collection has correct 'sync' event after one of its models save");
  668. });
  669. collection.create({id: 1});
  670. collection.off();
  671. });
  672. test("#1447 - create with wait adds model.", 1, function() {
  673. var collection = new Backbone.Collection;
  674. var model = new Backbone.Model;
  675. model.sync = function(method, model, options){ options.success(); };
  676. collection.on('add', function(){ ok(true); });
  677. collection.create(model, {wait: true});
  678. });
  679. test("#1448 - add sorts collection after merge.", 1, function() {
  680. var collection = new Backbone.Collection([
  681. {id: 1, x: 1},
  682. {id: 2, x: 2}
  683. ]);
  684. collection.comparator = function(model){ return model.get('x'); };
  685. collection.add({id: 1, x: 3}, {merge: true});
  686. deepEqual(collection.pluck('id'), [2, 1]);
  687. });
  688. test("#1655 - groupBy can be used with a string argument.", 3, function() {
  689. var collection = new Backbone.Collection([{x: 1}, {x: 2}]);
  690. var grouped = collection.groupBy('x');
  691. strictEqual(_.keys(grouped).length, 2);
  692. strictEqual(grouped[1][0].get('x'), 1);
  693. strictEqual(grouped[2][0].get('x'), 2);
  694. });
  695. test("#1655 - sortBy can be used with a string argument.", 1, function() {
  696. var collection = new Backbone.Collection([{x: 3}, {x: 1}, {x: 2}]);
  697. var values = _.map(collection.sortBy('x'), function(model) {
  698. return model.get('x');
  699. });
  700. deepEqual(values, [1, 2, 3]);
  701. });
  702. test("#1604 - Removal during iteration.", 0, function() {
  703. var collection = new Backbone.Collection([{}, {}]);
  704. collection.on('add', function() {
  705. collection.at(0).destroy();
  706. });
  707. collection.add({}, {at: 0});
  708. });
  709. test("#1638 - `sort` during `add` triggers correctly.", function() {
  710. var collection = new Backbone.Collection;
  711. collection.comparator = function(model) { return model.get('x'); };
  712. var added = [];
  713. collection.on('add', function(model) {
  714. model.set({x: 3});
  715. collection.sort();
  716. added.push(model.id);
  717. });
  718. collection.add([{id: 1, x: 1}, {id: 2, x: 2}]);
  719. deepEqual(added, [1, 2]);
  720. });
  721. test("fetch parses models by default", 1, function() {
  722. var model = {};
  723. var Collection = Backbone.Collection.extend({
  724. url: 'test',
  725. model: Backbone.Model.extend({
  726. parse: function(resp) {
  727. strictEqual(resp, model);
  728. }
  729. })
  730. });
  731. new Collection().fetch();
  732. this.ajaxSettings.success([model]);
  733. });
  734. test("`sort` shouldn't always fire on `add`", 1, function() {
  735. var c = new Backbone.Collection([{id: 1}, {id: 2}, {id: 3}], {
  736. comparator: 'id'
  737. });
  738. c.sort = function(){ ok(true); };
  739. c.add([]);
  740. c.add({id: 1});
  741. c.add([{id: 2}, {id: 3}]);
  742. c.add({id: 4});
  743. });
  744. test("#1407 parse option on constructor parses collection and models", 2, function() {
  745. var model = {
  746. namespace : [{id: 1}, {id:2}]
  747. };
  748. var Collection = Backbone.Collection.extend({
  749. model: Backbone.Model.extend({
  750. parse: function(model) {
  751. model.name = 'test';
  752. return model;
  753. }
  754. }),
  755. parse: function(model) {
  756. return model.namespace;
  757. }
  758. });
  759. var c = new Collection(model, {parse:true});
  760. equal(c.length, 2);
  761. equal(c.at(0).get('name'), 'test');
  762. });
  763. test("#1407 parse option on reset parses collection and models", 2, function() {
  764. var model = {
  765. namespace : [{id: 1}, {id:2}]
  766. };
  767. var Collection = Backbone.Collection.extend({
  768. model: Backbone.Model.extend({
  769. parse: function(model) {
  770. model.name = 'test';
  771. return model;
  772. }
  773. }),
  774. parse: function(model) {
  775. return model.namespace;
  776. }
  777. });
  778. var c = new Collection();
  779. c.reset(model, {parse:true});
  780. equal(c.length, 2);
  781. equal(c.at(0).get('name'), 'test');
  782. });
  783. test("Reset includes previous models in triggered event.", 1, function() {
  784. var model = new Backbone.Model();
  785. var collection = new Backbone.Collection([model])
  786. .on('reset', function(collection, options) {
  787. deepEqual(options.previousModels, [model]);
  788. });
  789. collection.reset([]);
  790. });
  791. test("set", function() {
  792. var m1 = new Backbone.Model();
  793. var m2 = new Backbone.Model({id: 2});
  794. var m3 = new Backbone.Model();
  795. var c = new Backbone.Collection([m1, m2]);
  796. // Test add/change/remove events
  797. c.on('add', function(model) {
  798. strictEqual(model, m3);
  799. });
  800. c.on('change', function(model) {
  801. strictEqual(model, m2);
  802. });
  803. c.on('remove', function(model) {
  804. strictEqual(model, m1);
  805. });
  806. // remove: false doesn't remove any models
  807. c.set([], {remove: false});
  808. strictEqual(c.length, 2);
  809. // add: false doesn't add any models
  810. c.set([m1, m2, m3], {add: false});
  811. strictEqual(c.length, 2);
  812. // merge: false doesn't change any models
  813. c.set([m1, {id: 2, a: 1}], {merge: false});
  814. strictEqual(m2.get('a'), void 0);
  815. // add: false, remove: false only merges existing models
  816. c.set([m1, {id: 2, a: 0}, m3, {id: 4}], {add: false, remove: false});
  817. strictEqual(c.length, 2);
  818. strictEqual(m2.get('a'), 0);
  819. // default options add/remove/merge as appropriate
  820. c.set([{id: 2, a: 1}, m3]);
  821. strictEqual(c.length, 2);
  822. strictEqual(m2.get('a'), 1);
  823. // Test removing models not passing an argument
  824. c.off('remove').on('remove', function(model) {
  825. ok(model === m2 || model === m3);
  826. });
  827. c.set([]);
  828. strictEqual(c.length, 0);
  829. });
  830. test("set with only cids", 3, function() {
  831. var m1 = new Backbone.Model;
  832. var m2 = new Backbone.Model;
  833. var c = new Backbone.Collection;
  834. c.set([m1, m2]);
  835. equal(c.length, 2);
  836. c.set([m1]);
  837. equal(c.length, 1);
  838. c.set([m1, m1, m1, m2, m2], {remove: false});
  839. equal(c.length, 2);
  840. });
  841. test("set with only idAttribute", 3, function() {
  842. var m1 = { _id: 1 };
  843. var m2 = { _id: 2 };
  844. var col = Backbone.Collection.extend({
  845. model: Backbone.Model.extend({
  846. idAttribute: '_id'
  847. })
  848. });
  849. var c = new col;
  850. c.set([m1, m2]);
  851. equal(c.length, 2);
  852. c.set([m1]);
  853. equal(c.length, 1);
  854. c.set([m1, m1, m1, m2, m2], {remove: false});
  855. equal(c.length, 2);
  856. });
  857. test("set + merge with default values defined", function() {
  858. var Model = Backbone.Model.extend({
  859. defaults: {
  860. key: 'value'
  861. }
  862. });
  863. var m = new Model({id: 1});
  864. var col = new Backbone.Collection([m], {model: Model});
  865. equal(col.first().get('key'), 'value');
  866. col.set({id: 1, key: 'other'});
  867. equal(col.first().get('key'), 'other');
  868. col.set({id: 1, other: 'value'});
  869. equal(col.first().get('key'), 'other');
  870. equal(col.length, 1);
  871. });
  872. test('merge without mutation', function () {
  873. var Model = Backbone.Model.extend({
  874. initialize: function (attrs, options) {
  875. if (attrs.child) {
  876. this.set('child', new Model(attrs.child, options), options);
  877. }
  878. }
  879. });
  880. var Collection = Backbone.Collection.extend({model: Model});
  881. var data = [{id: 1, child: {id: 2}}];
  882. var collection = new Collection(data);
  883. equal(collection.first().id, 1);
  884. collection.set(data);
  885. equal(collection.first().id, 1);
  886. collection.set([{id: 2, child: {id: 2}}].concat(data));
  887. deepEqual(collection.pluck('id'), [2, 1]);
  888. });
  889. test("`set` and model level `parse`", function() {
  890. var Model = Backbone.Model.extend({
  891. parse: function (res) { return res.model; }
  892. });
  893. var Collection = Backbone.Collection.extend({
  894. model: Model,
  895. parse: function (res) { return res.models; }
  896. });
  897. var model = new Model({id: 1});
  898. var collection = new Collection(model);
  899. collection.set({models: [
  900. {model: {id: 1}},
  901. {model: {id: 2}}
  902. ]}, {parse: true});
  903. equal(collection.first(), model);
  904. });
  905. test("`set` data is only parsed once", function() {
  906. var collection = new Backbone.Collection();
  907. collection.model = Backbone.Model.extend({
  908. parse: function (data) {
  909. equal(data.parsed, void 0);
  910. data.parsed = true;
  911. return data;
  912. }
  913. });
  914. collection.set({}, {parse: true});
  915. });
  916. test('`set` matches input order in the absence of a comparator', function () {
  917. var one = new Backbone.Model({id: 1});
  918. var two = new Backbone.Model({id: 2});
  919. var three = new Backbone.Model({id: 3});
  920. var collection = new Backbone.Collection([one, two, three]);
  921. collection.set([{id: 3}, {id: 2}, {id: 1}]);
  922. deepEqual(collection.models, [three, two, one]);
  923. collection.set([{id: 1}, {id: 2}]);
  924. deepEqual(collection.models, [one, two]);
  925. collection.set([two, three, one]);
  926. deepEqual(collection.models, [two, three, one]);
  927. collection.set([{id: 1}, {id: 2}], {remove: false});
  928. deepEqual(collection.models, [two, three, one]);
  929. collection.set([{id: 1}, {id: 2}, {id: 3}], {merge: false});
  930. deepEqual(collection.models, [one, two, three]);
  931. collection.set([three, two, one, {id: 4}], {add: false});
  932. deepEqual(collection.models, [one, two, three]);
  933. });
  934. test("#1894 - Push should not trigger a sort", 0, function() {
  935. var Collection = Backbone.Collection.extend({
  936. comparator: 'id',
  937. sort: function() {
  938. ok(false);
  939. }
  940. });
  941. new Collection().push({id: 1});
  942. });
  943. test("`set` with non-normal id", function() {
  944. var Collection = Backbone.Collection.extend({
  945. model: Backbone.Model.extend({idAttribute: '_id'})
  946. });
  947. var collection = new Collection({_id: 1});
  948. collection.set([{_id: 1, a: 1}], {add: false});
  949. equal(collection.first().get('a'), 1);
  950. });
  951. test("#1894 - `sort` can optionally be turned off", 0, function() {
  952. var Collection = Backbone.Collection.extend({
  953. comparator: 'id',
  954. sort: function() { ok(true); }
  955. });
  956. new Collection().add({id: 1}, {sort: false});
  957. });
  958. test("#1915 - `parse` data in the right order in `set`", function() {
  959. var collection = new (Backbone.Collection.extend({
  960. parse: function (data) {
  961. strictEqual(data.status, 'ok');
  962. return data.data;
  963. }
  964. }));
  965. var res = {status: 'ok', data:[{id: 1}]};
  966. collection.set(res, {parse: true});
  967. });
  968. asyncTest("#1939 - `parse` is passed `options`", 1, function () {
  969. var collection = new (Backbone.Collection.extend({
  970. url: '/',
  971. parse: function (data, options) {
  972. strictEqual(options.xhr.someHeader, 'headerValue');
  973. return data;
  974. }
  975. }));
  976. var ajax = Backbone.ajax;
  977. Backbone.ajax = function (params) {
  978. _.defer(params.success);
  979. return {someHeader: 'headerValue'};
  980. };
  981. collection.fetch({
  982. success: function () { start(); }
  983. });
  984. Backbone.ajax = ajax;
  985. });
  986. test("`add` only `sort`s when necessary", 2, function () {
  987. var collection = new (Backbone.Collection.extend({
  988. comparator: 'a'
  989. }))([{id: 1}, {id: 2}, {id: 3}]);
  990. collection.on('sort', function () { ok(true); });
  991. collection.add({id: 4}); // do sort, new model
  992. collection.add({id: 1, a: 1}, {merge: true}); // do sort, comparator change
  993. collection.add({id: 1, b: 1}, {merge: true}); // don't sort, no comparator change
  994. collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no comparator change
  995. collection.add(collection.models); // don't sort, nothing new
  996. collection.add(collection.models, {merge: true}); // don't sort
  997. });
  998. test("`add` only `sort`s when necessary with comparator function", 3, function () {
  999. var collection = new (Backbone.Collection.extend({
  1000. comparator: function(a, b) {
  1001. return a.get('a') > b.get('a') ? 1 : (a.get('a') < b.get('a') ? -1 : 0);
  1002. }
  1003. }))([{id: 1}, {id: 2}, {id: 3}]);
  1004. collection.on('sort', function () { ok(true); });
  1005. collection.add({id: 4}); // do sort, new model
  1006. collection.add({id: 1, a: 1}, {merge: true}); // do sort, model change
  1007. collection.add({id: 1, b: 1}, {merge: true}); // do sort, model change
  1008. collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no model change
  1009. collection.add(collection.models); // don't sort, nothing new
  1010. collection.add(collection.models, {merge: true}); // don't sort
  1011. });
  1012. test("Attach options to collection.", 2, function() {
  1013. var model = new Backbone.Model;
  1014. var comparator = function(){};
  1015. var collection = new Backbone.Collection([], {
  1016. model: model,
  1017. comparator: comparator
  1018. });
  1019. ok(collection.model === model);
  1020. ok(collection.comparator === comparator);
  1021. });
  1022. test("`add` overrides `set` flags", function () {
  1023. var collection = new Backbone.Collection();
  1024. collection.once('add', function (model, collection, options) {
  1025. collection.add({id: 2}, options);
  1026. });
  1027. collection.set({id: 1});
  1028. equal(collection.length, 2);
  1029. });
  1030. test("#2606 - Collection#create, success arguments", 1, function() {
  1031. var collection = new Backbone.Collection;
  1032. collection.url = 'test';
  1033. collection.create({}, {
  1034. success: function(model, resp, options) {
  1035. strictEqual(resp, 'response');
  1036. }
  1037. });
  1038. this.ajaxSettings.success('response');
  1039. });
  1040. });