PageRenderTime 53ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/test/backbone/model.js

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