PageRenderTime 62ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/test/backbone/test/model.js

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