PageRenderTime 76ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/app/public/js/vendor/backbone/test/model.js

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