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

/test/model.js

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