PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/test/model.js

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