AndOrWriteStore.js 29 KB

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