TransactionalCollection.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. /**
  3. * Licensed Materials - Property of IBM
  4. * IBM Cognos Products: BI Cloud (C) Copyright IBM Corp. 2014, 2017
  5. * US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
  6. */
  7. define(['underscore', '../../lib/@waca/dashboard-common/dist/core/Collection'], function (_, Collection) {
  8. var TransactionalCollection = null;
  9. /**
  10. * A collection which allow changes to be made within the context of a transaction
  11. *
  12. * @see Collection
  13. *
  14. */
  15. TransactionalCollection = Collection.extend({
  16. init: function init() {
  17. TransactionalCollection.inherited('init', this, arguments);
  18. },
  19. /**
  20. * Start a transaction on this collection. During a transaction modifications will be silent and the
  21. * user of the collection can be notified of all the changes during the transaction at the end of the transaction
  22. * by calling stopTransaction(...)
  23. */
  24. startTransaction: function startTransaction() {
  25. if (this._transactionLog) {
  26. throw new Error('A transaction is already started');
  27. }
  28. this._transactionLog = new Collection(this.toJSON(), { modelClass: this.model });
  29. },
  30. /**
  31. * Stop the transaction on this collection. If changes were made to this collection in the context of the transaction
  32. * then a 'reset' event will be emitted describing the changes.
  33. */
  34. stopTransaction: function stopTransaction() {
  35. if (!this._transactionLog) {
  36. throw new Error('No transaction to stop');
  37. }
  38. var transactionLog = this._transactionLog;
  39. this._transactionLog = null;
  40. TransactionalCollection.inherited('reset', this, [transactionLog.toJSON()]);
  41. }
  42. });
  43. // Mix-in an override for all the collection methods that delegate to the transaction log collection when
  44. // we are in the context of a transaction
  45. var collectionFns = _.union(['add', 'remove', 'reset', 'set', 'getModels', 'get', 'toJSON'], Collection._underscoreMethods, Collection._underscoreAttributeMethods);
  46. _.each(collectionFns, function (method) {
  47. TransactionalCollection.prototype[method] = function () {
  48. if (this._transactionLog) {
  49. return this._transactionLog[method].apply(this._transactionLog, arguments);
  50. }
  51. return TransactionalCollection.inherited(method, this, arguments);
  52. };
  53. });
  54. return TransactionalCollection;
  55. });
  56. //# sourceMappingURL=TransactionalCollection.js.map