PageRenderTime 69ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/test/model.js

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