PageRenderTime 27ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/test/model.js

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