ItemFileWriteStore.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. define(["../_base/lang", "../_base/declare", "../_base/array", "../_base/json", "../_base/kernel",
  2. "./ItemFileReadStore", "../date/stamp"
  3. ], function(lang, declare, arrayUtil, jsonUtil, kernel, ItemFileReadStore, dateStamp){
  4. // module:
  5. // dojo/data/ItemFileWriteStore
  6. return declare("dojo.data.ItemFileWriteStore", ItemFileReadStore, {
  7. // summary:
  8. // TODOC
  9. constructor: function(/* object */ keywordParameters){
  10. // keywordParameters:
  11. // The structure of the typeMap object is as follows:
  12. // | {
  13. // | type0: function || object,
  14. // | type1: function || object,
  15. // | ...
  16. // | typeN: function || object
  17. // | }
  18. // Where if it is a function, it is assumed to be an object constructor that takes the
  19. // value of _value as the initialization parameters. It is serialized assuming object.toString()
  20. // serialization. If it is an object, then it is assumed
  21. // to be an object of general form:
  22. // | {
  23. // | type: function, //constructor.
  24. // | deserialize: function(value) //The function that parses the value and constructs the object defined by type appropriately.
  25. // | serialize: function(object) //The function that converts the object back into the proper file format form.
  26. // | }
  27. // ItemFileWriteStore extends ItemFileReadStore to implement these additional dojo.data APIs
  28. this._features['dojo.data.api.Write'] = true;
  29. this._features['dojo.data.api.Notification'] = true;
  30. // For keeping track of changes so that we can implement isDirty and revert
  31. this._pending = {
  32. _newItems:{},
  33. _modifiedItems:{},
  34. _deletedItems:{}
  35. };
  36. if(!this._datatypeMap['Date'].serialize){
  37. this._datatypeMap['Date'].serialize = function(obj){
  38. return dateStamp.toISOString(obj, {zulu:true});
  39. };
  40. }
  41. //Disable only if explicitly set to false.
  42. if(keywordParameters && (keywordParameters.referenceIntegrity === false)){
  43. this.referenceIntegrity = false;
  44. }
  45. // this._saveInProgress is set to true, briefly, from when save() is first called to when it completes
  46. this._saveInProgress = false;
  47. },
  48. referenceIntegrity: true, //Flag that defaultly enabled reference integrity tracking. This way it can also be disabled pogrammatially or declaratively.
  49. _assert: function(/* boolean */ condition){
  50. if(!condition){
  51. throw new Error("assertion failed in ItemFileWriteStore");
  52. }
  53. },
  54. _getIdentifierAttribute: function(){
  55. // this._assert((identifierAttribute === Number) || (dojo.isString(identifierAttribute)));
  56. return this.getFeatures()['dojo.data.api.Identity'];
  57. },
  58. /* dojo/data/api/Write */
  59. newItem: function(/* Object? */ keywordArgs, /* Object? */ parentInfo){
  60. // summary:
  61. // See dojo/data/api/Write.newItem()
  62. this._assert(!this._saveInProgress);
  63. if(!this._loadFinished){
  64. // We need to do this here so that we'll be able to find out what
  65. // identifierAttribute was specified in the data file.
  66. this._forceLoad();
  67. }
  68. if(typeof keywordArgs != "object" && typeof keywordArgs != "undefined"){
  69. throw new Error("newItem() was passed something other than an object");
  70. }
  71. var newIdentity = null;
  72. var identifierAttribute = this._getIdentifierAttribute();
  73. if(identifierAttribute === Number){
  74. newIdentity = this._arrayOfAllItems.length;
  75. }else{
  76. newIdentity = keywordArgs[identifierAttribute];
  77. if(typeof newIdentity === "undefined"){
  78. throw new Error("newItem() was not passed an identity for the new item");
  79. }
  80. if(lang.isArray(newIdentity)){
  81. throw new Error("newItem() was not passed an single-valued identity");
  82. }
  83. }
  84. // make sure this identity is not already in use by another item, if identifiers were
  85. // defined in the file. Otherwise it would be the item count,
  86. // which should always be unique in this case.
  87. if(this._itemsByIdentity){
  88. this._assert(typeof this._itemsByIdentity[newIdentity] === "undefined");
  89. }
  90. this._assert(typeof this._pending._newItems[newIdentity] === "undefined");
  91. this._assert(typeof this._pending._deletedItems[newIdentity] === "undefined");
  92. var newItem = {};
  93. newItem[this._storeRefPropName] = this;
  94. newItem[this._itemNumPropName] = this._arrayOfAllItems.length;
  95. if(this._itemsByIdentity){
  96. this._itemsByIdentity[newIdentity] = newItem;
  97. //We have to set the identifier now, otherwise we can't look it
  98. //up at calls to setValueorValues in parentInfo handling.
  99. newItem[identifierAttribute] = [newIdentity];
  100. }
  101. this._arrayOfAllItems.push(newItem);
  102. //We need to construct some data for the onNew call too...
  103. var pInfo = null;
  104. // Now we need to check to see where we want to assign this thingm if any.
  105. if(parentInfo && parentInfo.parent && parentInfo.attribute){
  106. pInfo = {
  107. item: parentInfo.parent,
  108. attribute: parentInfo.attribute,
  109. oldValue: undefined
  110. };
  111. //See if it is multi-valued or not and handle appropriately
  112. //Generally, all attributes are multi-valued for this store
  113. //So, we only need to append if there are already values present.
  114. var values = this.getValues(parentInfo.parent, parentInfo.attribute);
  115. if(values && values.length > 0){
  116. var tempValues = values.slice(0, values.length);
  117. if(values.length === 1){
  118. pInfo.oldValue = values[0];
  119. }else{
  120. pInfo.oldValue = values.slice(0, values.length);
  121. }
  122. tempValues.push(newItem);
  123. this._setValueOrValues(parentInfo.parent, parentInfo.attribute, tempValues, false);
  124. pInfo.newValue = this.getValues(parentInfo.parent, parentInfo.attribute);
  125. }else{
  126. this._setValueOrValues(parentInfo.parent, parentInfo.attribute, newItem, false);
  127. pInfo.newValue = newItem;
  128. }
  129. }else{
  130. //Toplevel item, add to both top list as well as all list.
  131. newItem[this._rootItemPropName]=true;
  132. this._arrayOfTopLevelItems.push(newItem);
  133. }
  134. this._pending._newItems[newIdentity] = newItem;
  135. //Clone over the properties to the new item
  136. for(var key in keywordArgs){
  137. if(key === this._storeRefPropName || key === this._itemNumPropName){
  138. // Bummer, the user is trying to do something like
  139. // newItem({_S:"foo"}). Unfortunately, our superclass,
  140. // ItemFileReadStore, is already using _S in each of our items
  141. // to hold private info. To avoid a naming collision, we
  142. // need to move all our private info to some other property
  143. // of all the items/objects. So, we need to iterate over all
  144. // the items and do something like:
  145. // item.__S = item._S;
  146. // item._S = undefined;
  147. // But first we have to make sure the new "__S" variable is
  148. // not in use, which means we have to iterate over all the
  149. // items checking for that.
  150. throw new Error("encountered bug in ItemFileWriteStore.newItem");
  151. }
  152. var value = keywordArgs[key];
  153. if(!lang.isArray(value)){
  154. value = [value];
  155. }
  156. newItem[key] = value;
  157. if(this.referenceIntegrity){
  158. for(var i = 0; i < value.length; i++){
  159. var val = value[i];
  160. if(this.isItem(val)){
  161. this._addReferenceToMap(val, newItem, key);
  162. }
  163. }
  164. }
  165. }
  166. this.onNew(newItem, pInfo); // dojo/data/api/Notification call
  167. return newItem; // item
  168. },
  169. _removeArrayElement: function(/* Array */ array, /* anything */ element){
  170. var index = arrayUtil.indexOf(array, element);
  171. if(index != -1){
  172. array.splice(index, 1);
  173. return true;
  174. }
  175. return false;
  176. },
  177. deleteItem: function(/* dojo/data/api/Item */ item){
  178. // summary:
  179. // See dojo/data/api/Write.deleteItem()
  180. this._assert(!this._saveInProgress);
  181. this._assertIsItem(item);
  182. // Remove this item from the _arrayOfAllItems, but leave a null value in place
  183. // of the item, so as not to change the length of the array, so that in newItem()
  184. // we can still safely do: newIdentity = this._arrayOfAllItems.length;
  185. var indexInArrayOfAllItems = item[this._itemNumPropName];
  186. var identity = this.getIdentity(item);
  187. //If we have reference integrity on, we need to do reference cleanup for the deleted item
  188. if(this.referenceIntegrity){
  189. //First scan all the attributes of this items for references and clean them up in the map
  190. //As this item is going away, no need to track its references anymore.
  191. //Get the attributes list before we generate the backup so it
  192. //doesn't pollute the attributes list.
  193. var attributes = this.getAttributes(item);
  194. //Backup the map, we'll have to restore it potentially, in a revert.
  195. if(item[this._reverseRefMap]){
  196. item["backup_" + this._reverseRefMap] = lang.clone(item[this._reverseRefMap]);
  197. }
  198. //TODO: This causes a reversion problem. This list won't be restored on revert since it is
  199. //attached to the 'value'. item, not ours. Need to back tese up somehow too.
  200. //Maybe build a map of the backup of the entries and attach it to the deleted item to be restored
  201. //later. Or just record them and call _addReferenceToMap on them in revert.
  202. arrayUtil.forEach(attributes, function(attribute){
  203. arrayUtil.forEach(this.getValues(item, attribute), function(value){
  204. if(this.isItem(value)){
  205. //We have to back up all the references we had to others so they can be restored on a revert.
  206. if(!item["backupRefs_" + this._reverseRefMap]){
  207. item["backupRefs_" + this._reverseRefMap] = [];
  208. }
  209. item["backupRefs_" + this._reverseRefMap].push({id: this.getIdentity(value), attr: attribute});
  210. this._removeReferenceFromMap(value, item, attribute);
  211. }
  212. }, this);
  213. }, this);
  214. //Next, see if we have references to this item, if we do, we have to clean them up too.
  215. var references = item[this._reverseRefMap];
  216. if(references){
  217. //Look through all the items noted as references to clean them up.
  218. for(var itemId in references){
  219. var containingItem = null;
  220. if(this._itemsByIdentity){
  221. containingItem = this._itemsByIdentity[itemId];
  222. }else{
  223. containingItem = this._arrayOfAllItems[itemId];
  224. }
  225. //We have a reference to a containing item, now we have to process the
  226. //attributes and clear all references to the item being deleted.
  227. if(containingItem){
  228. for(var attribute in references[itemId]){
  229. var oldValues = this.getValues(containingItem, attribute) || [];
  230. var newValues = arrayUtil.filter(oldValues, function(possibleItem){
  231. return !(this.isItem(possibleItem) && this.getIdentity(possibleItem) == identity);
  232. }, this);
  233. //Remove the note of the reference to the item and set the values on the modified attribute.
  234. this._removeReferenceFromMap(item, containingItem, attribute);
  235. if(newValues.length < oldValues.length){
  236. this._setValueOrValues(containingItem, attribute, newValues, true);
  237. }
  238. }
  239. }
  240. }
  241. }
  242. }
  243. this._arrayOfAllItems[indexInArrayOfAllItems] = null;
  244. item[this._storeRefPropName] = null;
  245. if(this._itemsByIdentity){
  246. delete this._itemsByIdentity[identity];
  247. }
  248. this._pending._deletedItems[identity] = item;
  249. //Remove from the toplevel items, if necessary...
  250. if(item[this._rootItemPropName]){
  251. this._removeArrayElement(this._arrayOfTopLevelItems, item);
  252. }
  253. this.onDelete(item); // dojo/data/api/Notification call
  254. return true;
  255. },
  256. setValue: function(/* dojo/data/api/Item */ item, /* attribute-name-string */ attribute, /* almost anything */ value){
  257. // summary:
  258. // See dojo/data/api/Write.set()
  259. return this._setValueOrValues(item, attribute, value, true); // boolean
  260. },
  261. setValues: function(/* dojo/data/api/Item */ item, /* attribute-name-string */ attribute, /* array */ values){
  262. // summary:
  263. // See dojo/data/api/Write.setValues()
  264. return this._setValueOrValues(item, attribute, values, true); // boolean
  265. },
  266. unsetAttribute: function(/* dojo/data/api/Item */ item, /* attribute-name-string */ attribute){
  267. // summary:
  268. // See dojo/data/api/Write.unsetAttribute()
  269. return this._setValueOrValues(item, attribute, [], true);
  270. },
  271. _setValueOrValues: function(/* dojo/data/api/Item */ item, /* attribute-name-string */ attribute, /* anything */ newValueOrValues, /*boolean?*/ callOnSet){
  272. this._assert(!this._saveInProgress);
  273. // Check for valid arguments
  274. this._assertIsItem(item);
  275. this._assert(lang.isString(attribute));
  276. this._assert(typeof newValueOrValues !== "undefined");
  277. // Make sure the user isn't trying to change the item's identity
  278. var identifierAttribute = this._getIdentifierAttribute();
  279. if(attribute == identifierAttribute){
  280. throw new Error("ItemFileWriteStore does not have support for changing the value of an item's identifier.");
  281. }
  282. // To implement the Notification API, we need to make a note of what
  283. // the old attribute value was, so that we can pass that info when
  284. // we call the onSet method.
  285. var oldValueOrValues = this._getValueOrValues(item, attribute);
  286. var identity = this.getIdentity(item);
  287. if(!this._pending._modifiedItems[identity]){
  288. // Before we actually change the item, we make a copy of it to
  289. // record the original state, so that we'll be able to revert if
  290. // the revert method gets called. If the item has already been
  291. // modified then there's no need to do this now, since we already
  292. // have a record of the original state.
  293. var copyOfItemState = {};
  294. for(var key in item){
  295. if((key === this._storeRefPropName) || (key === this._itemNumPropName) || (key === this._rootItemPropName)){
  296. copyOfItemState[key] = item[key];
  297. }else if(key === this._reverseRefMap){
  298. copyOfItemState[key] = lang.clone(item[key]);
  299. }else{
  300. copyOfItemState[key] = item[key].slice(0, item[key].length);
  301. }
  302. }
  303. // Now mark the item as dirty, and save the copy of the original state
  304. this._pending._modifiedItems[identity] = copyOfItemState;
  305. }
  306. // Okay, now we can actually change this attribute on the item
  307. var success = false;
  308. if(lang.isArray(newValueOrValues) && newValueOrValues.length === 0){
  309. // If we were passed an empty array as the value, that counts
  310. // as "unsetting" the attribute, so we need to remove this
  311. // attribute from the item.
  312. success = delete item[attribute];
  313. newValueOrValues = undefined; // used in the onSet Notification call below
  314. if(this.referenceIntegrity && oldValueOrValues){
  315. var oldValues = oldValueOrValues;
  316. if(!lang.isArray(oldValues)){
  317. oldValues = [oldValues];
  318. }
  319. for(var i = 0; i < oldValues.length; i++){
  320. var value = oldValues[i];
  321. if(this.isItem(value)){
  322. this._removeReferenceFromMap(value, item, attribute);
  323. }
  324. }
  325. }
  326. }else{
  327. var newValueArray;
  328. if(lang.isArray(newValueOrValues)){
  329. // Unfortunately, it's not safe to just do this:
  330. // newValueArray = newValueOrValues;
  331. // Instead, we need to copy the array, which slice() does very nicely.
  332. // This is so that our internal data structure won't
  333. // get corrupted if the user mucks with the values array *after*
  334. // calling setValues().
  335. newValueArray = newValueOrValues.slice(0, newValueOrValues.length);
  336. }else{
  337. newValueArray = [newValueOrValues];
  338. }
  339. //We need to handle reference integrity if this is on.
  340. //In the case of set, we need to see if references were added or removed
  341. //and update the reference tracking map accordingly.
  342. if(this.referenceIntegrity){
  343. if(oldValueOrValues){
  344. var oldValues = oldValueOrValues;
  345. if(!lang.isArray(oldValues)){
  346. oldValues = [oldValues];
  347. }
  348. //Use an associative map to determine what was added/removed from the list.
  349. //Should be O(n) performant. First look at all the old values and make a list of them
  350. //Then for any item not in the old list, we add it. If it was already present, we remove it.
  351. //Then we pass over the map and any references left it it need to be removed (IE, no match in
  352. //the new values list).
  353. var map = {};
  354. arrayUtil.forEach(oldValues, function(possibleItem){
  355. if(this.isItem(possibleItem)){
  356. var id = this.getIdentity(possibleItem);
  357. map[id.toString()] = true;
  358. }
  359. }, this);
  360. arrayUtil.forEach(newValueArray, function(possibleItem){
  361. if(this.isItem(possibleItem)){
  362. var id = this.getIdentity(possibleItem);
  363. if(map[id.toString()]){
  364. delete map[id.toString()];
  365. }else{
  366. this._addReferenceToMap(possibleItem, item, attribute);
  367. }
  368. }
  369. }, this);
  370. for(var rId in map){
  371. var removedItem;
  372. if(this._itemsByIdentity){
  373. removedItem = this._itemsByIdentity[rId];
  374. }else{
  375. removedItem = this._arrayOfAllItems[rId];
  376. }
  377. this._removeReferenceFromMap(removedItem, item, attribute);
  378. }
  379. }else{
  380. //Everything is new (no old values) so we have to just
  381. //insert all the references, if any.
  382. for(var i = 0; i < newValueArray.length; i++){
  383. var value = newValueArray[i];
  384. if(this.isItem(value)){
  385. this._addReferenceToMap(value, item, attribute);
  386. }
  387. }
  388. }
  389. }
  390. item[attribute] = newValueArray;
  391. success = true;
  392. }
  393. // Now we make the dojo/data/api/Notification call
  394. if(callOnSet){
  395. this.onSet(item, attribute, oldValueOrValues, newValueOrValues);
  396. }
  397. return success; // boolean
  398. },
  399. _addReferenceToMap: function(/* dojo/data/api/Item */ refItem, /* dojo/data/api/Item */ parentItem, /* string */ attribute){
  400. // summary:
  401. // Method to add an reference map entry for an item and attribute.
  402. // description:
  403. // Method to add an reference map entry for an item and attribute.
  404. // refItem:
  405. // The item that is referenced.
  406. // parentItem:
  407. // The item that holds the new reference to refItem.
  408. // attribute:
  409. // The attribute on parentItem that contains the new reference.
  410. var parentId = this.getIdentity(parentItem);
  411. var references = refItem[this._reverseRefMap];
  412. if(!references){
  413. references = refItem[this._reverseRefMap] = {};
  414. }
  415. var itemRef = references[parentId];
  416. if(!itemRef){
  417. itemRef = references[parentId] = {};
  418. }
  419. itemRef[attribute] = true;
  420. },
  421. _removeReferenceFromMap: function(/* dojo/data/api/Item */ refItem, /* dojo/data/api/Item */ parentItem, /* string */ attribute){
  422. // summary:
  423. // Method to remove an reference map entry for an item and attribute.
  424. // description:
  425. // Method to remove an reference map entry for an item and attribute. This will
  426. // also perform cleanup on the map such that if there are no more references at all to
  427. // the item, its reference object and entry are removed.
  428. // refItem:
  429. // The item that is referenced.
  430. // parentItem:
  431. // The item holding a reference to refItem.
  432. // attribute:
  433. // The attribute on parentItem that contains the reference.
  434. var identity = this.getIdentity(parentItem);
  435. var references = refItem[this._reverseRefMap];
  436. var itemId;
  437. if(references){
  438. for(itemId in references){
  439. if(itemId == identity){
  440. delete references[itemId][attribute];
  441. if(this._isEmpty(references[itemId])){
  442. delete references[itemId];
  443. }
  444. }
  445. }
  446. if(this._isEmpty(references)){
  447. delete refItem[this._reverseRefMap];
  448. }
  449. }
  450. },
  451. _dumpReferenceMap: function(){
  452. // summary:
  453. // Function to dump the reverse reference map of all items in the store for debug purposes.
  454. // description:
  455. // Function to dump the reverse reference map of all items in the store for debug purposes.
  456. var i;
  457. for(i = 0; i < this._arrayOfAllItems.length; i++){
  458. var item = this._arrayOfAllItems[i];
  459. if(item && item[this._reverseRefMap]){
  460. console.log("Item: [" + this.getIdentity(item) + "] is referenced by: " + jsonUtil.toJson(item[this._reverseRefMap]));
  461. }
  462. }
  463. },
  464. _getValueOrValues: function(/* dojo/data/api/Item */ item, /* attribute-name-string */ attribute){
  465. var valueOrValues = undefined;
  466. if(this.hasAttribute(item, attribute)){
  467. var valueArray = this.getValues(item, attribute);
  468. if(valueArray.length == 1){
  469. valueOrValues = valueArray[0];
  470. }else{
  471. valueOrValues = valueArray;
  472. }
  473. }
  474. return valueOrValues;
  475. },
  476. _flatten: function(/* anything */ value){
  477. if(this.isItem(value)){
  478. // Given an item, return an serializable object that provides a
  479. // reference to the item.
  480. // For example, given kermit:
  481. // var kermit = store.newItem({id:2, name:"Kermit"});
  482. // we want to return
  483. // {_reference:2}
  484. return {_reference: this.getIdentity(value)};
  485. }else{
  486. if(typeof value === "object"){
  487. for(var type in this._datatypeMap){
  488. var typeMap = this._datatypeMap[type];
  489. if(lang.isObject(typeMap) && !lang.isFunction(typeMap)){
  490. if(value instanceof typeMap.type){
  491. if(!typeMap.serialize){
  492. throw new Error("ItemFileWriteStore: No serializer defined for type mapping: [" + type + "]");
  493. }
  494. return {_type: type, _value: typeMap.serialize(value)};
  495. }
  496. }else if(value instanceof typeMap){
  497. //SImple mapping, therefore, return as a toString serialization.
  498. return {_type: type, _value: value.toString()};
  499. }
  500. }
  501. }
  502. return value;
  503. }
  504. },
  505. _getNewFileContentString: function(){
  506. // summary:
  507. // Generate a string that can be saved to a file.
  508. // The result should look similar to:
  509. // http://trac.dojotoolkit.org/browser/dojo/trunk/tests/data/countries.json
  510. var serializableStructure = {};
  511. var identifierAttribute = this._getIdentifierAttribute();
  512. if(identifierAttribute !== Number){
  513. serializableStructure.identifier = identifierAttribute;
  514. }
  515. if(this._labelAttr){
  516. serializableStructure.label = this._labelAttr;
  517. }
  518. serializableStructure.items = [];
  519. for(var i = 0; i < this._arrayOfAllItems.length; ++i){
  520. var item = this._arrayOfAllItems[i];
  521. if(item !== null){
  522. var serializableItem = {};
  523. for(var key in item){
  524. if(key !== this._storeRefPropName && key !== this._itemNumPropName && key !== this._reverseRefMap && key !== this._rootItemPropName){
  525. var valueArray = this.getValues(item, key);
  526. if(valueArray.length == 1){
  527. serializableItem[key] = this._flatten(valueArray[0]);
  528. }else{
  529. var serializableArray = [];
  530. for(var j = 0; j < valueArray.length; ++j){
  531. serializableArray.push(this._flatten(valueArray[j]));
  532. serializableItem[key] = serializableArray;
  533. }
  534. }
  535. }
  536. }
  537. serializableStructure.items.push(serializableItem);
  538. }
  539. }
  540. var prettyPrint = true;
  541. return jsonUtil.toJson(serializableStructure, prettyPrint);
  542. },
  543. _isEmpty: function(something){
  544. // summary:
  545. // Function to determine if an array or object has no properties or values.
  546. // something:
  547. // The array or object to examine.
  548. var empty = true;
  549. if(lang.isObject(something)){
  550. var i;
  551. for(i in something){
  552. empty = false;
  553. break;
  554. }
  555. }else if(lang.isArray(something)){
  556. if(something.length > 0){
  557. empty = false;
  558. }
  559. }
  560. return empty; //boolean
  561. },
  562. save: function(/* object */ keywordArgs){
  563. // summary:
  564. // See dojo/data/api/Write.save()
  565. this._assert(!this._saveInProgress);
  566. // this._saveInProgress is set to true, briefly, from when save is first called to when it completes
  567. this._saveInProgress = true;
  568. var self = this;
  569. var saveCompleteCallback = function(){
  570. self._pending = {
  571. _newItems:{},
  572. _modifiedItems:{},
  573. _deletedItems:{}
  574. };
  575. self._saveInProgress = false; // must come after this._pending is cleared, but before any callbacks
  576. if(keywordArgs && keywordArgs.onComplete){
  577. var scope = keywordArgs.scope || kernel.global;
  578. keywordArgs.onComplete.call(scope);
  579. }
  580. };
  581. var saveFailedCallback = function(err){
  582. self._saveInProgress = false;
  583. if(keywordArgs && keywordArgs.onError){
  584. var scope = keywordArgs.scope || kernel.global;
  585. keywordArgs.onError.call(scope, err);
  586. }
  587. };
  588. if(this._saveEverything){
  589. var newFileContentString = this._getNewFileContentString();
  590. this._saveEverything(saveCompleteCallback, saveFailedCallback, newFileContentString);
  591. }
  592. if(this._saveCustom){
  593. this._saveCustom(saveCompleteCallback, saveFailedCallback);
  594. }
  595. if(!this._saveEverything && !this._saveCustom){
  596. // Looks like there is no user-defined save-handler function.
  597. // That's fine, it just means the datastore is acting as a "mock-write"
  598. // store -- changes get saved in memory but don't get saved to disk.
  599. saveCompleteCallback();
  600. }
  601. },
  602. revert: function(){
  603. // summary:
  604. // See dojo/data/api/Write.revert()
  605. this._assert(!this._saveInProgress);
  606. var identity;
  607. for(identity in this._pending._modifiedItems){
  608. // find the original item and the modified item that replaced it
  609. var copyOfItemState = this._pending._modifiedItems[identity];
  610. var modifiedItem = null;
  611. if(this._itemsByIdentity){
  612. modifiedItem = this._itemsByIdentity[identity];
  613. }else{
  614. modifiedItem = this._arrayOfAllItems[identity];
  615. }
  616. // Restore the original item into a full-fledged item again, we want to try to
  617. // keep the same object instance as if we don't it, causes bugs like #9022.
  618. copyOfItemState[this._storeRefPropName] = this;
  619. for(var key in modifiedItem){
  620. delete modifiedItem[key];
  621. }
  622. lang.mixin(modifiedItem, copyOfItemState);
  623. }
  624. var deletedItem;
  625. for(identity in this._pending._deletedItems){
  626. deletedItem = this._pending._deletedItems[identity];
  627. deletedItem[this._storeRefPropName] = this;
  628. var index = deletedItem[this._itemNumPropName];
  629. //Restore the reverse refererence map, if any.
  630. if(deletedItem["backup_" + this._reverseRefMap]){
  631. deletedItem[this._reverseRefMap] = deletedItem["backup_" + this._reverseRefMap];
  632. delete deletedItem["backup_" + this._reverseRefMap];
  633. }
  634. this._arrayOfAllItems[index] = deletedItem;
  635. if(this._itemsByIdentity){
  636. this._itemsByIdentity[identity] = deletedItem;
  637. }
  638. if(deletedItem[this._rootItemPropName]){
  639. this._arrayOfTopLevelItems.push(deletedItem);
  640. }
  641. }
  642. //We have to pass through it again and restore the reference maps after all the
  643. //undeletes have occurred.
  644. for(identity in this._pending._deletedItems){
  645. deletedItem = this._pending._deletedItems[identity];
  646. if(deletedItem["backupRefs_" + this._reverseRefMap]){
  647. arrayUtil.forEach(deletedItem["backupRefs_" + this._reverseRefMap], function(reference){
  648. var refItem;
  649. if(this._itemsByIdentity){
  650. refItem = this._itemsByIdentity[reference.id];
  651. }else{
  652. refItem = this._arrayOfAllItems[reference.id];
  653. }
  654. this._addReferenceToMap(refItem, deletedItem, reference.attr);
  655. }, this);
  656. delete deletedItem["backupRefs_" + this._reverseRefMap];
  657. }
  658. }
  659. for(identity in this._pending._newItems){
  660. var newItem = this._pending._newItems[identity];
  661. newItem[this._storeRefPropName] = null;
  662. // null out the new item, but don't change the array index so
  663. // so we can keep using _arrayOfAllItems.length.
  664. this._arrayOfAllItems[newItem[this._itemNumPropName]] = null;
  665. if(newItem[this._rootItemPropName]){
  666. this._removeArrayElement(this._arrayOfTopLevelItems, newItem);
  667. }
  668. if(this._itemsByIdentity){
  669. delete this._itemsByIdentity[identity];
  670. }
  671. }
  672. this._pending = {
  673. _newItems:{},
  674. _modifiedItems:{},
  675. _deletedItems:{}
  676. };
  677. return true; // boolean
  678. },
  679. isDirty: function(/* item? */ item){
  680. // summary:
  681. // See dojo/data/api/Write.isDirty()
  682. if(item){
  683. // return true if the item is dirty
  684. var identity = this.getIdentity(item);
  685. return new Boolean(this._pending._newItems[identity] ||
  686. this._pending._modifiedItems[identity] ||
  687. this._pending._deletedItems[identity]).valueOf(); // boolean
  688. }else{
  689. // return true if the store is dirty -- which means return true
  690. // if there are any new items, dirty items, or modified items
  691. return !this._isEmpty(this._pending._newItems) ||
  692. !this._isEmpty(this._pending._modifiedItems) ||
  693. !this._isEmpty(this._pending._deletedItems); // boolean
  694. }
  695. },
  696. /* dojo/data/api/Notification */
  697. onSet: function(/* dojo/data/api/Item */ item,
  698. /*attribute-name-string*/ attribute,
  699. /*object|array*/ oldValue,
  700. /*object|array*/ newValue){
  701. // summary:
  702. // See dojo/data/api/Notification.onSet()
  703. // No need to do anything. This method is here just so that the
  704. // client code can connect observers to it.
  705. },
  706. onNew: function(/* dojo/data/api/Item */ newItem, /*object?*/ parentInfo){
  707. // summary:
  708. // See dojo/data/api/Notification.onNew()
  709. // No need to do anything. This method is here just so that the
  710. // client code can connect observers to it.
  711. },
  712. onDelete: function(/* dojo/data/api/Item */ deletedItem){
  713. // summary:
  714. // See dojo/data/api/Notification.onDelete()
  715. // No need to do anything. This method is here just so that the
  716. // client code can connect observers to it.
  717. },
  718. close: function(/* object? */ request){
  719. // summary:
  720. // Over-ride of base close function of ItemFileReadStore to add in check for store state.
  721. // description:
  722. // Over-ride of base close function of ItemFileReadStore to add in check for store state.
  723. // If the store is still dirty (unsaved changes), then an error will be thrown instead of
  724. // clearing the internal state for reload from the url.
  725. //Clear if not dirty ... or throw an error
  726. if(this.clearOnClose){
  727. if(!this.isDirty()){
  728. this.inherited(arguments);
  729. }else{
  730. //Only throw an error if the store was dirty and we were loading from a url (cannot reload from url until state is saved).
  731. throw new Error("dojo.data.ItemFileWriteStore: There are unsaved changes present in the store. Please save or revert the changes before invoking close.");
  732. }
  733. }
  734. }
  735. });
  736. });