PageRenderTime 68ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/test/model.js

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