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

/test/model.js

https://github.com/harshniketseta/backbone
JavaScript | 1000 lines | 889 code | 110 blank | 1 comment | 13 complexity | 36e9c8a21b81c6f41b1aeea8b0efe678 MD5 | raw file
  1. $(document).ready(function() {
  2. var proxy = Backbone.Model.extend();
  3. var klass = Backbone.Collection.extend({
  4. url : function() { return '/collection'; }
  5. });
  6. var doc, collection;
  7. module("Backbone.Model", _.extend(new Environment, {
  8. setup: function() {
  9. Environment.prototype.setup.apply(this, arguments);
  10. doc = new proxy({
  11. id : '1-the-tempest',
  12. title : "The Tempest",
  13. author : "Bill Shakespeare",
  14. length : 123
  15. });
  16. collection = new klass();
  17. collection.add(doc);
  18. }
  19. }));
  20. test("initialize", 3, function() {
  21. var Model = Backbone.Model.extend({
  22. initialize: function() {
  23. this.one = 1;
  24. equal(this.collection, collection);
  25. }
  26. });
  27. var model = new Model({}, {collection: collection});
  28. equal(model.one, 1);
  29. equal(model.collection, collection);
  30. });
  31. test("initialize with attributes and options", 1, function() {
  32. var Model = Backbone.Model.extend({
  33. initialize: function(attributes, options) {
  34. this.one = options.one;
  35. }
  36. });
  37. var model = new Model({}, {one: 1});
  38. equal(model.one, 1);
  39. });
  40. test("initialize with parsed attributes", 1, function() {
  41. var Model = Backbone.Model.extend({
  42. parse: function(obj) {
  43. obj.value += 1;
  44. return obj;
  45. }
  46. });
  47. var model = new Model({value: 1}, {parse: true});
  48. equal(model.get('value'), 2);
  49. });
  50. test("initialize with defaults", 2, function() {
  51. var Model = Backbone.Model.extend({
  52. defaults: {
  53. first_name: 'Unknown',
  54. last_name: 'Unknown'
  55. }
  56. });
  57. var model = new Model({'first_name': 'John'});
  58. equal(model.get('first_name'), 'John');
  59. equal(model.get('last_name'), 'Unknown');
  60. });
  61. test("parse can return null", 1, function() {
  62. var Model = Backbone.Model.extend({
  63. parse: function(obj) {
  64. obj.value += 1;
  65. return null;
  66. }
  67. });
  68. var model = new Model({value: 1}, {parse: true});
  69. equal(JSON.stringify(model.toJSON()), "{}");
  70. });
  71. test("url", 3, function() {
  72. doc.urlRoot = null;
  73. equal(doc.url(), '/collection/1-the-tempest');
  74. doc.collection.url = '/collection/';
  75. equal(doc.url(), '/collection/1-the-tempest');
  76. doc.collection = null;
  77. raises(function() { doc.url(); });
  78. doc.collection = collection;
  79. });
  80. test("url when using urlRoot, and uri encoding", 2, function() {
  81. var Model = Backbone.Model.extend({
  82. urlRoot: '/collection'
  83. });
  84. var model = new Model();
  85. equal(model.url(), '/collection');
  86. model.set({id: '+1+'});
  87. equal(model.url(), '/collection/%2B1%2B');
  88. });
  89. test("url when using urlRoot as a function to determine urlRoot at runtime", 2, function() {
  90. var Model = Backbone.Model.extend({
  91. urlRoot: function() {
  92. return '/nested/' + this.get('parent_id') + '/collection';
  93. }
  94. });
  95. var model = new Model({parent_id: 1});
  96. equal(model.url(), '/nested/1/collection');
  97. model.set({id: 2});
  98. equal(model.url(), '/nested/1/collection/2');
  99. });
  100. test("clone", 10, function() {
  101. var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
  102. var b = a.clone();
  103. equal(a.get('foo'), 1);
  104. equal(a.get('bar'), 2);
  105. equal(a.get('baz'), 3);
  106. equal(b.get('foo'), a.get('foo'), "Foo should be the same on the clone.");
  107. equal(b.get('bar'), a.get('bar'), "Bar should be the same on the clone.");
  108. equal(b.get('baz'), a.get('baz'), "Baz should be the same on the clone.");
  109. a.set({foo : 100});
  110. equal(a.get('foo'), 100);
  111. equal(b.get('foo'), 1, "Changing a parent attribute does not change the clone.");
  112. var foo = new Backbone.Model({p: 1});
  113. var bar = new Backbone.Model({p: 2});
  114. bar.set(foo.clone().attributes, {unset: true});
  115. equal(foo.get('p'), 1);
  116. equal(bar.get('p'), undefined);
  117. });
  118. test("isNew", 6, function() {
  119. var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
  120. ok(a.isNew(), "it should be new");
  121. a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3, 'id': -5 });
  122. ok(!a.isNew(), "any defined ID is legal, negative or positive");
  123. a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3, 'id': 0 });
  124. ok(!a.isNew(), "any defined ID is legal, including zero");
  125. ok( new Backbone.Model({ }).isNew(), "is true when there is no id");
  126. ok(!new Backbone.Model({ 'id': 2 }).isNew(), "is false for a positive integer");
  127. ok(!new Backbone.Model({ 'id': -5 }).isNew(), "is false for a negative integer");
  128. });
  129. test("get", 2, function() {
  130. equal(doc.get('title'), 'The Tempest');
  131. equal(doc.get('author'), 'Bill Shakespeare');
  132. });
  133. test("escape", 5, function() {
  134. equal(doc.escape('title'), 'The Tempest');
  135. doc.set({audience: 'Bill & Bob'});
  136. equal(doc.escape('audience'), 'Bill & Bob');
  137. doc.set({audience: 'Tim > Joan'});
  138. equal(doc.escape('audience'), 'Tim > Joan');
  139. doc.set({audience: 10101});
  140. equal(doc.escape('audience'), '10101');
  141. doc.unset('audience');
  142. equal(doc.escape('audience'), '');
  143. });
  144. test("has", 10, function() {
  145. var model = new Backbone.Model();
  146. strictEqual(model.has('name'), false);
  147. model.set({
  148. '0': 0,
  149. '1': 1,
  150. 'true': true,
  151. 'false': false,
  152. 'empty': '',
  153. 'name': 'name',
  154. 'null': null,
  155. 'undefined': undefined
  156. });
  157. strictEqual(model.has('0'), true);
  158. strictEqual(model.has('1'), true);
  159. strictEqual(model.has('true'), true);
  160. strictEqual(model.has('false'), true);
  161. strictEqual(model.has('empty'), true);
  162. strictEqual(model.has('name'), true);
  163. model.unset('name');
  164. strictEqual(model.has('name'), false);
  165. strictEqual(model.has('null'), false);
  166. strictEqual(model.has('undefined'), false);
  167. });
  168. test("set and unset", 8, function() {
  169. var a = new Backbone.Model({id: 'id', foo: 1, bar: 2, baz: 3});
  170. var changeCount = 0;
  171. a.on("change:foo", function() { changeCount += 1; });
  172. a.set({'foo': 2});
  173. ok(a.get('foo') == 2, "Foo should have changed.");
  174. ok(changeCount == 1, "Change count should have incremented.");
  175. a.set({'foo': 2}); // set with value that is not new shouldn't fire change event
  176. ok(a.get('foo') == 2, "Foo should NOT have changed, still 2");
  177. ok(changeCount == 1, "Change count should NOT have incremented.");
  178. a.validate = function(attrs) {
  179. equal(attrs.foo, void 0, "validate:true passed while unsetting");
  180. };
  181. a.unset('foo', {validate: true});
  182. equal(a.get('foo'), void 0, "Foo should have changed");
  183. delete a.validate;
  184. ok(changeCount == 2, "Change count should have incremented for unset.");
  185. a.unset('id');
  186. equal(a.id, undefined, "Unsetting the id should remove the id property.");
  187. });
  188. test("set triggers changes in the correct order", function() {
  189. var value = null;
  190. var model = new Backbone.Model;
  191. model.on('last', function(){ value = 'last'; });
  192. model.on('first', function(){ value = 'first'; });
  193. model.trigger('first');
  194. model.trigger('last');
  195. equal(value, 'last');
  196. });
  197. test("set falsy values in the correct order", 1, function() {
  198. var model = new Backbone.Model({result: 'result'});
  199. model.on('change', function() {
  200. equal(model.changed.result, false);
  201. });
  202. model.set({result: void 0}, {silent: true});
  203. model.set({result: null}, {silent: true});
  204. model.set({result: false}, {silent: true});
  205. model.change();
  206. });
  207. test("multiple unsets", 1, function() {
  208. var i = 0;
  209. var counter = function(){ i++; };
  210. var model = new Backbone.Model({a: 1});
  211. model.on("change:a", counter);
  212. model.set({a: 2});
  213. model.unset('a');
  214. model.unset('a');
  215. equal(i, 2, 'Unset does not fire an event for missing attributes.');
  216. });
  217. test("unset and changedAttributes", 2, function() {
  218. var model = new Backbone.Model({a: 1});
  219. model.unset('a', {silent: true});
  220. var changedAttributes = model.changedAttributes();
  221. ok('a' in changedAttributes, 'changedAttributes should contain unset properties');
  222. changedAttributes = model.changedAttributes();
  223. ok('a' in changedAttributes, 'changedAttributes should contain unset properties when running changedAttributes again after an unset.');
  224. });
  225. test("using a non-default id attribute.", 5, function() {
  226. var MongoModel = Backbone.Model.extend({idAttribute : '_id'});
  227. var model = new MongoModel({id: 'eye-dee', _id: 25, title: 'Model'});
  228. equal(model.get('id'), 'eye-dee');
  229. equal(model.id, 25);
  230. equal(model.isNew(), false);
  231. model.unset('_id');
  232. equal(model.id, undefined);
  233. equal(model.isNew(), true);
  234. });
  235. test("set an empty string", 1, function() {
  236. var model = new Backbone.Model({name : "Model"});
  237. model.set({name : ''});
  238. equal(model.get('name'), '');
  239. });
  240. test("clear", 3, function() {
  241. var changed;
  242. var model = new Backbone.Model({id: 1, name : "Model"});
  243. model.on("change:name", function(){ changed = true; });
  244. model.on("change", function() {
  245. var changedAttrs = model.changedAttributes();
  246. ok('name' in changedAttrs);
  247. });
  248. model.clear();
  249. equal(changed, true);
  250. equal(model.get('name'), undefined);
  251. });
  252. test("defaults", 4, function() {
  253. var Defaulted = Backbone.Model.extend({
  254. defaults: {
  255. "one": 1,
  256. "two": 2
  257. }
  258. });
  259. var model = new Defaulted({two: null});
  260. equal(model.get('one'), 1);
  261. equal(model.get('two'), 2);
  262. Defaulted = Backbone.Model.extend({
  263. defaults: function() {
  264. return {
  265. "one": 3,
  266. "two": 4
  267. };
  268. }
  269. });
  270. model = new Defaulted({two: null});
  271. equal(model.get('one'), 3);
  272. equal(model.get('two'), 4);
  273. });
  274. test("change, hasChanged, changedAttributes, previous, previousAttributes", 12, function() {
  275. var model = new Backbone.Model({name : "Tim", age : 10});
  276. equal(model.changedAttributes(), false);
  277. model.on('change', function() {
  278. ok(model.hasChanged('name'), 'name changed');
  279. ok(!model.hasChanged('age'), 'age did not');
  280. ok(_.isEqual(model.changedAttributes(), {name : 'Rob'}), 'changedAttributes returns the changed attrs');
  281. equal(model.previous('name'), 'Tim');
  282. ok(_.isEqual(model.previousAttributes(), {name : "Tim", age : 10}), 'previousAttributes is correct');
  283. });
  284. equal(model.hasChanged(), false);
  285. equal(model.hasChanged(undefined), false);
  286. model.set({name : 'Rob'}, {silent : true});
  287. equal(model.hasChanged(), true);
  288. equal(model.hasChanged(undefined), true);
  289. equal(model.hasChanged('name'), true);
  290. model.change();
  291. equal(model.get('name'), 'Rob');
  292. });
  293. test("changedAttributes", 3, function() {
  294. var model = new Backbone.Model({a: 'a', b: 'b'});
  295. equal(model.changedAttributes(), false);
  296. equal(model.changedAttributes({a: 'a'}), false);
  297. equal(model.changedAttributes({a: 'b'}).a, 'b');
  298. });
  299. test("change with options", 2, function() {
  300. var value;
  301. var model = new Backbone.Model({name: 'Rob'});
  302. model.on('change', function(model, options) {
  303. value = options.prefix + model.get('name');
  304. });
  305. model.set({name: 'Bob'}, {silent: true});
  306. model.change({prefix: 'Mr. '});
  307. equal(value, 'Mr. Bob');
  308. model.set({name: 'Sue'}, {prefix: 'Ms. '});
  309. equal(value, 'Ms. Sue');
  310. });
  311. test("change after initialize", 1, function () {
  312. var changed = 0;
  313. var attrs = {id: 1, label: 'c'};
  314. var obj = new Backbone.Model(attrs);
  315. obj.on('change', function() { changed += 1; });
  316. obj.set(attrs);
  317. equal(changed, 0);
  318. });
  319. test("save within change event", 1, function () {
  320. var env = this;
  321. var model = new Backbone.Model({firstName : "Taylor", lastName: "Swift"});
  322. model.url = '/test';
  323. model.on('change', function () {
  324. model.save();
  325. ok(_.isEqual(env.syncArgs.model, model));
  326. });
  327. model.set({lastName: 'Hicks'});
  328. });
  329. test("validate after save", 2, function() {
  330. var lastError, model = new Backbone.Model();
  331. model.validate = function(attrs) {
  332. if (attrs.admin) return "Can't change admin status.";
  333. };
  334. model.sync = function(method, model, options) {
  335. options.success.call(this, {admin: true});
  336. };
  337. model.on('invalid', function(model, error) {
  338. lastError = error;
  339. });
  340. model.save(null);
  341. equal(lastError, "Can't change admin status.");
  342. equal(model.validationError, "Can't change admin status.");
  343. });
  344. test("save", 2, function() {
  345. doc.save({title : "Henry V"});
  346. equal(this.syncArgs.method, 'update');
  347. ok(_.isEqual(this.syncArgs.model, doc));
  348. });
  349. test("save with PATCH", function() {
  350. doc.clear().set({id: 1, a: 1, b: 2, c: 3, d: 4});
  351. doc.save();
  352. equal(this.syncArgs.method, 'update');
  353. equal(this.syncArgs.options.attrs, undefined);
  354. doc.save({b: 2, d: 4}, {patch: true});
  355. equal(this.syncArgs.method, 'patch');
  356. equal(_.size(this.syncArgs.options.attrs), 2);
  357. equal(this.syncArgs.options.attrs.d, 4);
  358. equal(this.syncArgs.options.attrs.a, undefined);
  359. equal(this.ajaxSettings.data, "{\"b\":2,\"d\":4}");
  360. });
  361. test("save in positional style", 1, function() {
  362. var model = new Backbone.Model();
  363. model.sync = function(method, model, options) {
  364. options.success();
  365. };
  366. model.save('title', 'Twelfth Night');
  367. equal(model.get('title'), 'Twelfth Night');
  368. });
  369. test("fetch", 2, function() {
  370. doc.fetch();
  371. equal(this.syncArgs.method, 'read');
  372. ok(_.isEqual(this.syncArgs.model, doc));
  373. });
  374. test("destroy", 3, function() {
  375. doc.destroy();
  376. equal(this.syncArgs.method, 'delete');
  377. ok(_.isEqual(this.syncArgs.model, doc));
  378. var newModel = new Backbone.Model;
  379. equal(newModel.destroy(), false);
  380. });
  381. test("non-persisted destroy", 1, function() {
  382. var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
  383. a.sync = function() { throw "should not be called"; };
  384. a.destroy();
  385. ok(true, "non-persisted model should not call sync");
  386. });
  387. test("validate", function() {
  388. var lastError;
  389. var model = new Backbone.Model();
  390. model.validate = function(attrs) {
  391. if (attrs.admin != this.get('admin')) return "Can't change admin status.";
  392. };
  393. model.on('invalid', function(model, error) {
  394. lastError = error;
  395. });
  396. var result = model.set({a: 100});
  397. equal(result, model);
  398. equal(model.get('a'), 100);
  399. equal(lastError, undefined);
  400. result = model.set({admin: true});
  401. equal(model.get('admin'), true);
  402. result = model.set({a: 200, admin: false}, {validate:true});
  403. equal(lastError, "Can't change admin status.");
  404. equal(result, false);
  405. equal(model.get('a'), 100);
  406. });
  407. test("validate on unset and clear", 6, function() {
  408. var error;
  409. var model = new Backbone.Model({name: "One"});
  410. model.validate = function(attrs) {
  411. if (!attrs.name) {
  412. error = true;
  413. return "No thanks.";
  414. }
  415. };
  416. model.set({name: "Two"});
  417. equal(model.get('name'), 'Two');
  418. equal(error, undefined);
  419. model.unset('name', {validate: true});
  420. equal(error, true);
  421. equal(model.get('name'), 'Two');
  422. model.clear({validate:true});
  423. equal(model.get('name'), 'Two');
  424. delete model.validate;
  425. model.clear();
  426. equal(model.get('name'), undefined);
  427. });
  428. test("validate with error callback", 8, function() {
  429. var lastError, boundError;
  430. var model = new Backbone.Model();
  431. model.validate = function(attrs) {
  432. if (attrs.admin) return "Can't change admin status.";
  433. };
  434. model.on('invalid', function(model, error) {
  435. boundError = true;
  436. });
  437. var result = model.set({a: 100}, {validate:true});
  438. equal(result, model);
  439. equal(model.get('a'), 100);
  440. equal(model.validationError, null);
  441. equal(boundError, undefined);
  442. result = model.set({a: 200, admin: true}, {validate:true});
  443. equal(result, false);
  444. equal(model.get('a'), 100);
  445. equal(model.validationError, "Can't change admin status.");
  446. equal(boundError, true);
  447. });
  448. test("defaults always extend attrs (#459)", 2, function() {
  449. var Defaulted = Backbone.Model.extend({
  450. defaults: {one: 1},
  451. initialize : function(attrs, opts) {
  452. equal(this.attributes.one, 1);
  453. }
  454. });
  455. var providedattrs = new Defaulted({});
  456. var emptyattrs = new Defaulted();
  457. });
  458. test("Inherit class properties", 6, function() {
  459. var Parent = Backbone.Model.extend({
  460. instancePropSame: function() {},
  461. instancePropDiff: function() {}
  462. }, {
  463. classProp: function() {}
  464. });
  465. var Child = Parent.extend({
  466. instancePropDiff: function() {}
  467. });
  468. var adult = new Parent;
  469. var kid = new Child;
  470. equal(Child.classProp, Parent.classProp);
  471. notEqual(Child.classProp, undefined);
  472. equal(kid.instancePropSame, adult.instancePropSame);
  473. notEqual(kid.instancePropSame, undefined);
  474. notEqual(Child.prototype.instancePropDiff, Parent.prototype.instancePropDiff);
  475. notEqual(Child.prototype.instancePropDiff, undefined);
  476. });
  477. test("Nested change events don't clobber previous attributes", 4, function() {
  478. new Backbone.Model()
  479. .on('change:state', function(model, newState) {
  480. equal(model.previous('state'), undefined);
  481. equal(newState, 'hello');
  482. // Fire a nested change event.
  483. model.set({other: 'whatever'});
  484. })
  485. .on('change:state', function(model, newState) {
  486. equal(model.previous('state'), undefined);
  487. equal(newState, 'hello');
  488. })
  489. .set({state: 'hello'});
  490. });
  491. test("hasChanged/set should use same comparison", 2, function() {
  492. var changed = 0, model = new Backbone.Model({a: null});
  493. model.on('change', function() {
  494. ok(this.hasChanged('a'));
  495. })
  496. .on('change:a', function() {
  497. changed++;
  498. })
  499. .set({a: undefined});
  500. equal(changed, 1);
  501. });
  502. test("#582, #425, change:attribute callbacks should fire after all changes have occurred", 9, function() {
  503. var model = new Backbone.Model;
  504. var assertion = function() {
  505. equal(model.get('a'), 'a');
  506. equal(model.get('b'), 'b');
  507. equal(model.get('c'), 'c');
  508. };
  509. model.on('change:a', assertion);
  510. model.on('change:b', assertion);
  511. model.on('change:c', assertion);
  512. model.set({a: 'a', b: 'b', c: 'c'});
  513. });
  514. test("#871, set with attributes property", 1, function() {
  515. var model = new Backbone.Model();
  516. model.set({attributes: true});
  517. ok(model.has('attributes'));
  518. });
  519. test("set value regardless of equality/change", 1, function() {
  520. var model = new Backbone.Model({x: []});
  521. var a = [];
  522. model.set({x: a});
  523. ok(model.get('x') === a);
  524. });
  525. test("set same value does not trigger change", 0, function() {
  526. var model = new Backbone.Model({x: 1});
  527. model.on('change change:x', function() { ok(false); });
  528. model.set({x: 1});
  529. model.set({x: 1});
  530. });
  531. test("unset does not fire a change for undefined attributes", 0, function() {
  532. var model = new Backbone.Model({x: undefined});
  533. model.on('change:x', function(){ ok(false); });
  534. model.unset('x');
  535. });
  536. test("set: undefined values", 1, function() {
  537. var model = new Backbone.Model({x: undefined});
  538. ok('x' in model.attributes);
  539. });
  540. test("change fires change:attr", 1, function() {
  541. var model = new Backbone.Model({x: 1});
  542. model.set({x: 2}, {silent: true});
  543. model.on('change:x', function(){ ok(true); });
  544. model.change();
  545. });
  546. test("hasChanged is false after original values are set", 2, function() {
  547. var model = new Backbone.Model({x: 1});
  548. model.on('change:x', function(){ ok(false); });
  549. model.set({x: 2}, {silent: true});
  550. ok(model.hasChanged());
  551. model.set({x: 1}, {silent: true});
  552. ok(!model.hasChanged());
  553. });
  554. test("save with `wait` succeeds without `validate`", 1, function() {
  555. var model = new Backbone.Model();
  556. model.url = '/test';
  557. model.save({x: 1}, {wait: true});
  558. ok(this.syncArgs.model === model);
  559. });
  560. test("`hasChanged` for falsey keys", 2, function() {
  561. var model = new Backbone.Model();
  562. model.set({x: true}, {silent: true});
  563. ok(!model.hasChanged(0));
  564. ok(!model.hasChanged(''));
  565. });
  566. test("`previous` for falsey keys", 2, function() {
  567. var model = new Backbone.Model({0: true, '': true});
  568. model.set({0: false, '': false}, {silent: true});
  569. equal(model.previous(0), true);
  570. equal(model.previous(''), true);
  571. });
  572. test("`save` with `wait` sends correct attributes", 5, function() {
  573. var changed = 0;
  574. var model = new Backbone.Model({x: 1, y: 2});
  575. model.url = '/test';
  576. model.on('change:x', function() { changed++; });
  577. model.save({x: 3}, {wait: true});
  578. deepEqual(JSON.parse(this.ajaxSettings.data), {x: 3, y: 2});
  579. equal(model.get('x'), 1);
  580. equal(changed, 0);
  581. this.syncArgs.options.success({});
  582. equal(model.get('x'), 3);
  583. equal(changed, 1);
  584. });
  585. test("a failed `save` with `wait` doesn't leave attributes behind", 1, function() {
  586. var model = new Backbone.Model;
  587. model.url = '/test';
  588. model.save({x: 1}, {wait: true});
  589. equal(model.get('x'), void 0);
  590. });
  591. test("#1030 - `save` with `wait` results in correct attributes if success is called during sync", 2, function() {
  592. var model = new Backbone.Model({x: 1, y: 2});
  593. model.sync = function(method, model, options) {
  594. options.success();
  595. };
  596. model.on("change:x", function() { ok(true); });
  597. model.save({x: 3}, {wait: true});
  598. equal(model.get('x'), 3);
  599. });
  600. test("save with wait validates attributes", function() {
  601. var model = new Backbone.Model();
  602. model.url = '/test';
  603. model.validate = function() { ok(true); };
  604. model.save({x: 1}, {wait: true});
  605. });
  606. test("nested `set` during `'change:attr'`", 2, function() {
  607. var events = [];
  608. var model = new Backbone.Model();
  609. model.on('all', function(event) { events.push(event); });
  610. model.on('change', function() {
  611. model.set({z: true}, {silent:true});
  612. });
  613. model.on('change:x', function() {
  614. model.set({y: true});
  615. });
  616. model.set({x: true});
  617. deepEqual(events, ['change:y', 'change:x', 'change']);
  618. events = [];
  619. model.change();
  620. deepEqual(events, ['change:z', 'change']);
  621. });
  622. test("nested `change` only fires once", 1, function() {
  623. var model = new Backbone.Model();
  624. model.on('change', function() {
  625. ok(true);
  626. model.change();
  627. });
  628. model.set({x: true});
  629. });
  630. test("no `'change'` event if no changes", 0, function() {
  631. var model = new Backbone.Model();
  632. model.on('change', function() { ok(false); });
  633. model.change();
  634. });
  635. test("nested `set` during `'change'`", 6, function() {
  636. var count = 0;
  637. var model = new Backbone.Model();
  638. model.on('change', function() {
  639. switch(count++) {
  640. case 0:
  641. deepEqual(this.changedAttributes(), {x: true});
  642. equal(model.previous('x'), undefined);
  643. model.set({y: true});
  644. break;
  645. case 1:
  646. deepEqual(this.changedAttributes(), {y: true});
  647. equal(model.previous('x'), true);
  648. model.set({z: true});
  649. break;
  650. case 2:
  651. deepEqual(this.changedAttributes(), {z: true});
  652. equal(model.previous('y'), true);
  653. break;
  654. default:
  655. ok(false);
  656. }
  657. });
  658. model.set({x: true});
  659. });
  660. test("nested `'change'` with silent", 3, function() {
  661. var count = 0;
  662. var model = new Backbone.Model();
  663. model.on('change:y', function() { ok(true); });
  664. model.on('change', function() {
  665. switch(count++) {
  666. case 0:
  667. deepEqual(this.changedAttributes(), {x: true});
  668. model.set({y: true}, {silent: true});
  669. break;
  670. case 1:
  671. deepEqual(this.changedAttributes(), {y: true, z: true});
  672. break;
  673. default:
  674. ok(false);
  675. }
  676. });
  677. model.set({x: true});
  678. model.set({z: true});
  679. });
  680. test("nested `'change:attr'` with silent", 1, function() {
  681. var model = new Backbone.Model();
  682. model.on('change:y', function(){ ok(true); });
  683. model.on('change', function() {
  684. model.set({y: true}, {silent: true});
  685. model.set({z: true});
  686. });
  687. model.set({x: true});
  688. });
  689. test("multiple nested changes with silent", 1, function() {
  690. var model = new Backbone.Model();
  691. model.on('change:x', function() {
  692. model.set({y: 1}, {silent: true});
  693. model.set({y: 2});
  694. });
  695. model.on('change:y', function(model, val) {
  696. equal(val, 2);
  697. });
  698. model.set({x: true});
  699. model.change();
  700. });
  701. test("multiple nested changes with silent", 2, function() {
  702. var changes = [];
  703. var model = new Backbone.Model();
  704. model.on('change:b', function(model, val) { changes.push(val); });
  705. model.on('change', function() {
  706. model.set({b: 1});
  707. model.set({b: 2}, {silent: true});
  708. });
  709. model.set({b: 0});
  710. deepEqual(changes, [0, 1]);
  711. model.change();
  712. deepEqual(changes, [0, 1, 2, 1]);
  713. });
  714. test("nested set multiple times", 1, function() {
  715. var model = new Backbone.Model();
  716. model.on('change:b', function() {
  717. ok(true);
  718. });
  719. model.on('change:a', function() {
  720. model.set({b: true});
  721. model.set({b: true});
  722. });
  723. model.set({a: true});
  724. });
  725. test("#1122 - clear does not alter options.", 1, function() {
  726. var model = new Backbone.Model();
  727. var options = {};
  728. model.clear(options);
  729. ok(!options.unset);
  730. });
  731. test("#1122 - unset does not alter options.", 1, function() {
  732. var model = new Backbone.Model();
  733. var options = {};
  734. model.unset('x', options);
  735. ok(!options.unset);
  736. });
  737. test("#1355 - `options` is passed to success callbacks", 3, function() {
  738. var model = new Backbone.Model();
  739. var opts = {
  740. success: function( model, resp, options ) {
  741. ok(options);
  742. }
  743. };
  744. model.sync = function(method, model, options) {
  745. options.success();
  746. };
  747. model.save({id: 1}, opts);
  748. model.fetch(opts);
  749. model.destroy(opts);
  750. });
  751. test("#1412 - Trigger 'sync' event.", 3, function() {
  752. var model = new Backbone.Model({id: 1});
  753. model.url = '/test';
  754. model.on('sync', function(){ ok(true); });
  755. Backbone.ajax = function(settings){ settings.success(); };
  756. model.fetch();
  757. model.save();
  758. model.destroy();
  759. });
  760. test("#1365 - Destroy: New models execute success callback.", 2, function() {
  761. new Backbone.Model()
  762. .on('sync', function() { ok(false); })
  763. .on('destroy', function(){ ok(true); })
  764. .destroy({ success: function(){ ok(true); }});
  765. });
  766. test("#1433 - Save: An invalid model cannot be persisted.", 1, function() {
  767. var model = new Backbone.Model;
  768. model.validate = function(){ return 'invalid'; };
  769. model.sync = function(){ ok(false); };
  770. strictEqual(model.save(), false);
  771. });
  772. test("#1377 - Save without attrs triggers 'error'.", 1, function() {
  773. var Model = Backbone.Model.extend({
  774. url: '/test/',
  775. sync: function(method, model, options){ options.success(); },
  776. validate: function(){ return 'invalid'; }
  777. });
  778. var model = new Model({id: 1});
  779. model.on('invalid', function(){ ok(true); });
  780. model.save();
  781. });
  782. test("#1545 - `undefined` can be passed to a model constructor without coersion", function() {
  783. var Model = Backbone.Model.extend({
  784. defaults: { one: 1 },
  785. initialize : function(attrs, opts) {
  786. equal(attrs, undefined);
  787. }
  788. });
  789. var emptyattrs = new Model();
  790. var undefinedattrs = new Model(undefined);
  791. });
  792. asyncTest("#1478 - Model `save` does not trigger change on unchanged attributes", 0, function() {
  793. var Model = Backbone.Model.extend({
  794. sync: function(method, model, options) {
  795. setTimeout(function(){
  796. options.success();
  797. start();
  798. }, 0);
  799. }
  800. });
  801. new Model({x: true})
  802. .on('change:x', function(){ ok(false); })
  803. .save(null, {wait: true});
  804. });
  805. test("#1664 - Changing from one value, silently to another, back to original does not trigger change.", 0, function() {
  806. var model = new Backbone.Model({x:1});
  807. model.on('change:x', function() { ok(false); });
  808. model.set({x:2},{silent:true});
  809. model.set({x:3},{silent:true});
  810. model.set({x:1});
  811. });
  812. test("#1664 - multiple silent changes nested inside a change event", 2, function() {
  813. var changes = [];
  814. var model = new Backbone.Model();
  815. model.on('change', function() {
  816. model.set({a:'c'}, {silent:true});
  817. model.set({b:2}, {silent:true});
  818. model.unset('c', {silent:true});
  819. model.set({a:'a'}, {silent:true});
  820. model.set({b:1}, {silent:true});
  821. model.set({c:'item'}, {silent:true});
  822. });
  823. model.on('change:a change:b change:c', function(model, val) { changes.push(val); });
  824. model.set({a:'a', b:1, c:'item'});
  825. deepEqual(changes, ['a',1,'item']);
  826. model.change();
  827. deepEqual(changes, ['a',1,'item']);
  828. });
  829. test("#1791 - `attributes` is available for `parse`", function() {
  830. var Model = Backbone.Model.extend({
  831. parse: function() { this.has('a'); } // shouldn't throw an error
  832. });
  833. var model = new Model(null, {parse: true});
  834. expect(0);
  835. });
  836. test("silent changes in last `change` event back to original does not trigger change", 2, function() {
  837. var changes = [];
  838. var model = new Backbone.Model();
  839. model.on('change:a change:b change:c', function(model, val) { changes.push(val); });
  840. model.on('change', function() {
  841. model.set({a:'c'}, {silent:true});
  842. });
  843. model.set({a:'a'});
  844. deepEqual(changes, ['a']);
  845. model.set({a:'a'}, {silent:true});
  846. model.change();
  847. deepEqual(changes, ['a']);
  848. });
  849. test("#1943 change calculations should use _.isEqual", function() {
  850. var model = new Backbone.Model({a: {key: 'value'}});
  851. model.set('a', {key:'value'}, {silent:true});
  852. equal(model.changedAttributes(), false);
  853. });
  854. test("#1964 - final `change` event is always fired, regardless of interim changes", 1, function () {
  855. var model = new Backbone.Model();
  856. model.on('change:property', function() {
  857. model.set('property', 'bar');
  858. });
  859. model.on('change', function() {
  860. ok(true);
  861. });
  862. model.set('property', 'foo');
  863. });
  864. test("isValid", function() {
  865. var model = new Backbone.Model({valid: true});
  866. model.validate = function(attrs) {
  867. if (!attrs.valid) return "invalid";
  868. };
  869. equal(model.isValid(), true);
  870. equal(model.set({valid: false}, {validate:true}), false);
  871. equal(model.isValid(), true);
  872. model.set({valid:false});
  873. equal(model.isValid(), false);
  874. ok(!model.set('valid', false, {validate: true}));
  875. });
  876. test("#1179 - isValid returns true in the absence of validate.", 1, function() {
  877. var model = new Backbone.Model();
  878. model.validate = null;
  879. ok(model.isValid());
  880. });
  881. test("#1961 - Creating a model with {validate:true} will call validate and use the error callback", function () {
  882. var Model = Backbone.Model.extend({
  883. validate: function (attrs) {
  884. if (attrs.id === 1) return "This shouldn't happen";
  885. }
  886. });
  887. var model = new Model({id: 1}, {validate: true});
  888. equal(model.validationError, "This shouldn't happen");
  889. });
  890. });