ItemFileWriteStore.js 29 KB

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