ItemFileReadStore.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  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.ItemFileReadStore"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
  7. dojo._hasResource["dojo.data.ItemFileReadStore"] = true;
  8. dojo.provide("dojo.data.ItemFileReadStore");
  9. dojo.require("dojo.data.util.filter");
  10. dojo.require("dojo.data.util.simpleFetch");
  11. dojo.require("dojo.date.stamp");
  12. dojo.declare("dojo.data.ItemFileReadStore", null,{
  13. // summary:
  14. // The ItemFileReadStore implements the dojo.data.api.Read API and reads
  15. // data from JSON files that have contents in this format --
  16. // { items: [
  17. // { name:'Kermit', color:'green', age:12, friends:['Gonzo', {_reference:{name:'Fozzie Bear'}}]},
  18. // { name:'Fozzie Bear', wears:['hat', 'tie']},
  19. // { name:'Miss Piggy', pets:'Foo-Foo'}
  20. // ]}
  21. // Note that it can also contain an 'identifer' property that specified which attribute on the items
  22. // in the array of items that acts as the unique identifier for that item.
  23. //
  24. constructor: function(/* Object */ keywordParameters){
  25. // summary: constructor
  26. // keywordParameters: {url: String}
  27. // keywordParameters: {data: jsonObject}
  28. // keywordParameters: {typeMap: object)
  29. // The structure of the typeMap object is as follows:
  30. // {
  31. // type0: function || object,
  32. // type1: function || object,
  33. // ...
  34. // typeN: function || object
  35. // }
  36. // Where if it is a function, it is assumed to be an object constructor that takes the
  37. // value of _value as the initialization parameters. If it is an object, then it is assumed
  38. // to be an object of general form:
  39. // {
  40. // type: function, //constructor.
  41. // deserialize: function(value) //The function that parses the value and constructs the object defined by type appropriately.
  42. // }
  43. this._arrayOfAllItems = [];
  44. this._arrayOfTopLevelItems = [];
  45. this._loadFinished = false;
  46. this._jsonFileUrl = keywordParameters.url;
  47. this._ccUrl = keywordParameters.url;
  48. this.url = keywordParameters.url;
  49. this._jsonData = keywordParameters.data;
  50. this.data = null;
  51. this._datatypeMap = keywordParameters.typeMap || {};
  52. if(!this._datatypeMap['Date']){
  53. //If no default mapping for dates, then set this as default.
  54. //We use the dojo.date.stamp here because the ISO format is the 'dojo way'
  55. //of generically representing dates.
  56. this._datatypeMap['Date'] = {
  57. type: Date,
  58. deserialize: function(value){
  59. return dojo.date.stamp.fromISOString(value);
  60. }
  61. };
  62. }
  63. this._features = {'dojo.data.api.Read':true, 'dojo.data.api.Identity':true};
  64. this._itemsByIdentity = null;
  65. this._storeRefPropName = "_S"; // Default name for the store reference to attach to every item.
  66. this._itemNumPropName = "_0"; // Default Item Id for isItem to attach to every item.
  67. this._rootItemPropName = "_RI"; // Default Item Id for isItem to attach to every item.
  68. this._reverseRefMap = "_RRM"; // Default attribute for constructing a reverse reference map for use with reference integrity
  69. this._loadInProgress = false; //Got to track the initial load to prevent duelling loads of the dataset.
  70. this._queuedFetches = [];
  71. if(keywordParameters.urlPreventCache !== undefined){
  72. this.urlPreventCache = keywordParameters.urlPreventCache?true:false;
  73. }
  74. if(keywordParameters.hierarchical !== undefined){
  75. this.hierarchical = keywordParameters.hierarchical?true:false;
  76. }
  77. if(keywordParameters.clearOnClose){
  78. this.clearOnClose = true;
  79. }
  80. if("failOk" in keywordParameters){
  81. this.failOk = keywordParameters.failOk?true:false;
  82. }
  83. },
  84. url: "", // use "" rather than undefined for the benefit of the parser (#3539)
  85. //Internal var, crossCheckUrl. Used so that setting either url or _jsonFileUrl, can still trigger a reload
  86. //when clearOnClose and close is used.
  87. _ccUrl: "",
  88. data: null, // define this so that the parser can populate it
  89. typeMap: null, //Define so parser can populate.
  90. //Parameter to allow users to specify if a close call should force a reload or not.
  91. //By default, it retains the old behavior of not clearing if close is called. But
  92. //if set true, the store will be reset to default state. Note that by doing this,
  93. //all item handles will become invalid and a new fetch must be issued.
  94. clearOnClose: false,
  95. //Parameter to allow specifying if preventCache should be passed to the xhrGet call or not when loading data from a url.
  96. //Note this does not mean the store calls the server on each fetch, only that the data load has preventCache set as an option.
  97. //Added for tracker: #6072
  98. urlPreventCache: false,
  99. //Parameter for specifying that it is OK for the xhrGet call to fail silently.
  100. failOk: false,
  101. //Parameter to indicate to process data from the url as hierarchical
  102. //(data items can contain other data items in js form). Default is true
  103. //for backwards compatibility. False means only root items are processed
  104. //as items, all child objects outside of type-mapped objects and those in
  105. //specific reference format, are left straight JS data objects.
  106. hierarchical: true,
  107. _assertIsItem: function(/* item */ item){
  108. // summary:
  109. // This function tests whether the item passed in is indeed an item in the store.
  110. // item:
  111. // The item to test for being contained by the store.
  112. if(!this.isItem(item)){
  113. throw new Error("dojo.data.ItemFileReadStore: Invalid item argument.");
  114. }
  115. },
  116. _assertIsAttribute: function(/* attribute-name-string */ attribute){
  117. // summary:
  118. // This function tests whether the item passed in is indeed a valid 'attribute' like type for the store.
  119. // attribute:
  120. // The attribute to test for being contained by the store.
  121. if(typeof attribute !== "string"){
  122. throw new Error("dojo.data.ItemFileReadStore: Invalid attribute argument.");
  123. }
  124. },
  125. getValue: function( /* item */ item,
  126. /* attribute-name-string */ attribute,
  127. /* value? */ defaultValue){
  128. // summary:
  129. // See dojo.data.api.Read.getValue()
  130. var values = this.getValues(item, attribute);
  131. return (values.length > 0)?values[0]:defaultValue; // mixed
  132. },
  133. getValues: function(/* item */ item,
  134. /* attribute-name-string */ attribute){
  135. // summary:
  136. // See dojo.data.api.Read.getValues()
  137. this._assertIsItem(item);
  138. this._assertIsAttribute(attribute);
  139. // Clone it before returning. refs: #10474
  140. return (item[attribute] || []).slice(0); // Array
  141. },
  142. getAttributes: function(/* item */ item){
  143. // summary:
  144. // See dojo.data.api.Read.getAttributes()
  145. this._assertIsItem(item);
  146. var attributes = [];
  147. for(var key in item){
  148. // Save off only the real item attributes, not the special id marks for O(1) isItem.
  149. if((key !== this._storeRefPropName) && (key !== this._itemNumPropName) && (key !== this._rootItemPropName) && (key !== this._reverseRefMap)){
  150. attributes.push(key);
  151. }
  152. }
  153. return attributes; // Array
  154. },
  155. hasAttribute: function( /* item */ item,
  156. /* attribute-name-string */ attribute){
  157. // summary:
  158. // See dojo.data.api.Read.hasAttribute()
  159. this._assertIsItem(item);
  160. this._assertIsAttribute(attribute);
  161. return (attribute in item);
  162. },
  163. containsValue: function(/* item */ item,
  164. /* attribute-name-string */ attribute,
  165. /* anything */ value){
  166. // summary:
  167. // See dojo.data.api.Read.containsValue()
  168. var regexp = undefined;
  169. if(typeof value === "string"){
  170. regexp = dojo.data.util.filter.patternToRegExp(value, false);
  171. }
  172. return this._containsValue(item, attribute, value, regexp); //boolean.
  173. },
  174. _containsValue: function( /* item */ item,
  175. /* attribute-name-string */ attribute,
  176. /* anything */ value,
  177. /* RegExp?*/ regexp){
  178. // summary:
  179. // Internal function for looking at the values contained by the item.
  180. // description:
  181. // Internal function for looking at the values contained by the item. This
  182. // function allows for denoting if the comparison should be case sensitive for
  183. // strings or not (for handling filtering cases where string case should not matter)
  184. //
  185. // item:
  186. // The data item to examine for attribute values.
  187. // attribute:
  188. // The attribute to inspect.
  189. // value:
  190. // The value to match.
  191. // regexp:
  192. // Optional regular expression generated off value if value was of string type to handle wildcarding.
  193. // If present and attribute values are string, then it can be used for comparison instead of 'value'
  194. return dojo.some(this.getValues(item, attribute), function(possibleValue){
  195. if(possibleValue !== null && !dojo.isObject(possibleValue) && regexp){
  196. if(possibleValue.toString().match(regexp)){
  197. return true; // Boolean
  198. }
  199. }else if(value === possibleValue){
  200. return true; // Boolean
  201. }
  202. });
  203. },
  204. isItem: function(/* anything */ something){
  205. // summary:
  206. // See dojo.data.api.Read.isItem()
  207. if(something && something[this._storeRefPropName] === this){
  208. if(this._arrayOfAllItems[something[this._itemNumPropName]] === something){
  209. return true;
  210. }
  211. }
  212. return false; // Boolean
  213. },
  214. isItemLoaded: function(/* anything */ something){
  215. // summary:
  216. // See dojo.data.api.Read.isItemLoaded()
  217. return this.isItem(something); //boolean
  218. },
  219. loadItem: function(/* object */ keywordArgs){
  220. // summary:
  221. // See dojo.data.api.Read.loadItem()
  222. this._assertIsItem(keywordArgs.item);
  223. },
  224. getFeatures: function(){
  225. // summary:
  226. // See dojo.data.api.Read.getFeatures()
  227. return this._features; //Object
  228. },
  229. getLabel: function(/* item */ item){
  230. // summary:
  231. // See dojo.data.api.Read.getLabel()
  232. if(this._labelAttr && this.isItem(item)){
  233. return this.getValue(item,this._labelAttr); //String
  234. }
  235. return undefined; //undefined
  236. },
  237. getLabelAttributes: function(/* item */ item){
  238. // summary:
  239. // See dojo.data.api.Read.getLabelAttributes()
  240. if(this._labelAttr){
  241. return [this._labelAttr]; //array
  242. }
  243. return null; //null
  244. },
  245. _fetchItems: function( /* Object */ keywordArgs,
  246. /* Function */ findCallback,
  247. /* Function */ errorCallback){
  248. // summary:
  249. // See dojo.data.util.simpleFetch.fetch()
  250. var self = this,
  251. filter = function(requestArgs, arrayOfItems){
  252. var items = [],
  253. i, key;
  254. if(requestArgs.query){
  255. var value,
  256. ignoreCase = requestArgs.queryOptions ? requestArgs.queryOptions.ignoreCase : false;
  257. //See if there are any string values that can be regexp parsed first to avoid multiple regexp gens on the
  258. //same value for each item examined. Much more efficient.
  259. var regexpList = {};
  260. for(key in requestArgs.query){
  261. value = requestArgs.query[key];
  262. if(typeof value === "string"){
  263. regexpList[key] = dojo.data.util.filter.patternToRegExp(value, ignoreCase);
  264. }else if(value instanceof RegExp){
  265. regexpList[key] = value;
  266. }
  267. }
  268. for(i = 0; i < arrayOfItems.length; ++i){
  269. var match = true;
  270. var candidateItem = arrayOfItems[i];
  271. if(candidateItem === null){
  272. match = false;
  273. }else{
  274. for(key in requestArgs.query){
  275. value = requestArgs.query[key];
  276. if(!self._containsValue(candidateItem, key, value, regexpList[key])){
  277. match = false;
  278. }
  279. }
  280. }
  281. if(match){
  282. items.push(candidateItem);
  283. }
  284. }
  285. findCallback(items, requestArgs);
  286. }else{
  287. // We want a copy to pass back in case the parent wishes to sort the array.
  288. // We shouldn't allow resort of the internal list, so that multiple callers
  289. // can get lists and sort without affecting each other. We also need to
  290. // filter out any null values that have been left as a result of deleteItem()
  291. // calls in ItemFileWriteStore.
  292. for(i = 0; i < arrayOfItems.length; ++i){
  293. var item = arrayOfItems[i];
  294. if(item !== null){
  295. items.push(item);
  296. }
  297. }
  298. findCallback(items, requestArgs);
  299. }
  300. };
  301. if(this._loadFinished){
  302. filter(keywordArgs, this._getItemsArray(keywordArgs.queryOptions));
  303. }else{
  304. //Do a check on the JsonFileUrl and crosscheck it.
  305. //If it doesn't match the cross-check, it needs to be updated
  306. //This allows for either url or _jsonFileUrl to he changed to
  307. //reset the store load location. Done this way for backwards
  308. //compatibility. People use _jsonFileUrl (even though officially
  309. //private.
  310. if(this._jsonFileUrl !== this._ccUrl){
  311. dojo.deprecated("dojo.data.ItemFileReadStore: ",
  312. "To change the url, set the url property of the store," +
  313. " not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
  314. this._ccUrl = this._jsonFileUrl;
  315. this.url = this._jsonFileUrl;
  316. }else if(this.url !== this._ccUrl){
  317. this._jsonFileUrl = this.url;
  318. this._ccUrl = this.url;
  319. }
  320. //See if there was any forced reset of data.
  321. if(this.data != null){
  322. this._jsonData = this.data;
  323. this.data = null;
  324. }
  325. if(this._jsonFileUrl){
  326. //If fetches come in before the loading has finished, but while
  327. //a load is in progress, we have to defer the fetching to be
  328. //invoked in the callback.
  329. if(this._loadInProgress){
  330. this._queuedFetches.push({args: keywordArgs, filter: filter});
  331. }else{
  332. this._loadInProgress = true;
  333. var getArgs = {
  334. url: self._jsonFileUrl,
  335. handleAs: "json-comment-optional",
  336. preventCache: this.urlPreventCache,
  337. failOk: this.failOk
  338. };
  339. var getHandler = dojo.xhrGet(getArgs);
  340. getHandler.addCallback(function(data){
  341. try{
  342. self._getItemsFromLoadedData(data);
  343. self._loadFinished = true;
  344. self._loadInProgress = false;
  345. filter(keywordArgs, self._getItemsArray(keywordArgs.queryOptions));
  346. self._handleQueuedFetches();
  347. }catch(e){
  348. self._loadFinished = true;
  349. self._loadInProgress = false;
  350. errorCallback(e, keywordArgs);
  351. }
  352. });
  353. getHandler.addErrback(function(error){
  354. self._loadInProgress = false;
  355. errorCallback(error, keywordArgs);
  356. });
  357. //Wire up the cancel to abort of the request
  358. //This call cancel on the deferred if it hasn't been called
  359. //yet and then will chain to the simple abort of the
  360. //simpleFetch keywordArgs
  361. var oldAbort = null;
  362. if(keywordArgs.abort){
  363. oldAbort = keywordArgs.abort;
  364. }
  365. keywordArgs.abort = function(){
  366. var df = getHandler;
  367. if(df && df.fired === -1){
  368. df.cancel();
  369. df = null;
  370. }
  371. if(oldAbort){
  372. oldAbort.call(keywordArgs);
  373. }
  374. };
  375. }
  376. }else if(this._jsonData){
  377. try{
  378. this._loadFinished = true;
  379. this._getItemsFromLoadedData(this._jsonData);
  380. this._jsonData = null;
  381. filter(keywordArgs, this._getItemsArray(keywordArgs.queryOptions));
  382. }catch(e){
  383. errorCallback(e, keywordArgs);
  384. }
  385. }else{
  386. errorCallback(new Error("dojo.data.ItemFileReadStore: No JSON source data was provided as either URL or a nested Javascript object."), keywordArgs);
  387. }
  388. }
  389. },
  390. _handleQueuedFetches: function(){
  391. // summary:
  392. // Internal function to execute delayed request in the store.
  393. //Execute any deferred fetches now.
  394. if(this._queuedFetches.length > 0){
  395. for(var i = 0; i < this._queuedFetches.length; i++){
  396. var fData = this._queuedFetches[i],
  397. delayedQuery = fData.args,
  398. delayedFilter = fData.filter;
  399. if(delayedFilter){
  400. delayedFilter(delayedQuery, this._getItemsArray(delayedQuery.queryOptions));
  401. }else{
  402. this.fetchItemByIdentity(delayedQuery);
  403. }
  404. }
  405. this._queuedFetches = [];
  406. }
  407. },
  408. _getItemsArray: function(/*object?*/queryOptions){
  409. // summary:
  410. // Internal function to determine which list of items to search over.
  411. // queryOptions: The query options parameter, if any.
  412. if(queryOptions && queryOptions.deep){
  413. return this._arrayOfAllItems;
  414. }
  415. return this._arrayOfTopLevelItems;
  416. },
  417. close: function(/*dojo.data.api.Request || keywordArgs || null */ request){
  418. // summary:
  419. // See dojo.data.api.Read.close()
  420. if(this.clearOnClose &&
  421. this._loadFinished &&
  422. !this._loadInProgress){
  423. //Reset all internalsback to default state. This will force a reload
  424. //on next fetch. This also checks that the data or url param was set
  425. //so that the store knows it can get data. Without one of those being set,
  426. //the next fetch will trigger an error.
  427. if(((this._jsonFileUrl == "" || this._jsonFileUrl == null) &&
  428. (this.url == "" || this.url == null)
  429. ) && this.data == null){
  430. console.debug("dojo.data.ItemFileReadStore: WARNING! Data reload " +
  431. " information has not been provided." +
  432. " Please set 'url' or 'data' to the appropriate value before" +
  433. " the next fetch");
  434. }
  435. this._arrayOfAllItems = [];
  436. this._arrayOfTopLevelItems = [];
  437. this._loadFinished = false;
  438. this._itemsByIdentity = null;
  439. this._loadInProgress = false;
  440. this._queuedFetches = [];
  441. }
  442. },
  443. _getItemsFromLoadedData: function(/* Object */ dataObject){
  444. // summary:
  445. // Function to parse the loaded data into item format and build the internal items array.
  446. // description:
  447. // Function to parse the loaded data into item format and build the internal items array.
  448. //
  449. // dataObject:
  450. // The JS data object containing the raw data to convery into item format.
  451. //
  452. // returns: array
  453. // Array of items in store item format.
  454. // First, we define a couple little utility functions...
  455. var addingArrays = false,
  456. self = this;
  457. function valueIsAnItem(/* anything */ aValue){
  458. // summary:
  459. // Given any sort of value that could be in the raw json data,
  460. // return true if we should interpret the value as being an
  461. // item itself, rather than a literal value or a reference.
  462. // example:
  463. // | false == valueIsAnItem("Kermit");
  464. // | false == valueIsAnItem(42);
  465. // | false == valueIsAnItem(new Date());
  466. // | false == valueIsAnItem({_type:'Date', _value:'1802-05-14'});
  467. // | false == valueIsAnItem({_reference:'Kermit'});
  468. // | true == valueIsAnItem({name:'Kermit', color:'green'});
  469. // | true == valueIsAnItem({iggy:'pop'});
  470. // | true == valueIsAnItem({foo:42});
  471. var isItem = (
  472. (aValue !== null) &&
  473. (typeof aValue === "object") &&
  474. (!dojo.isArray(aValue) || addingArrays) &&
  475. (!dojo.isFunction(aValue)) &&
  476. (aValue.constructor == Object || dojo.isArray(aValue)) &&
  477. (typeof aValue._reference === "undefined") &&
  478. (typeof aValue._type === "undefined") &&
  479. (typeof aValue._value === "undefined") &&
  480. self.hierarchical
  481. );
  482. return isItem;
  483. }
  484. function addItemAndSubItemsToArrayOfAllItems(/* Item */ anItem){
  485. self._arrayOfAllItems.push(anItem);
  486. for(var attribute in anItem){
  487. var valueForAttribute = anItem[attribute];
  488. if(valueForAttribute){
  489. if(dojo.isArray(valueForAttribute)){
  490. var valueArray = valueForAttribute;
  491. for(var k = 0; k < valueArray.length; ++k){
  492. var singleValue = valueArray[k];
  493. if(valueIsAnItem(singleValue)){
  494. addItemAndSubItemsToArrayOfAllItems(singleValue);
  495. }
  496. }
  497. }else{
  498. if(valueIsAnItem(valueForAttribute)){
  499. addItemAndSubItemsToArrayOfAllItems(valueForAttribute);
  500. }
  501. }
  502. }
  503. }
  504. }
  505. this._labelAttr = dataObject.label;
  506. // We need to do some transformations to convert the data structure
  507. // that we read from the file into a format that will be convenient
  508. // to work with in memory.
  509. // Step 1: Walk through the object hierarchy and build a list of all items
  510. var i,
  511. item;
  512. this._arrayOfAllItems = [];
  513. this._arrayOfTopLevelItems = dataObject.items;
  514. for(i = 0; i < this._arrayOfTopLevelItems.length; ++i){
  515. item = this._arrayOfTopLevelItems[i];
  516. if(dojo.isArray(item)){
  517. addingArrays = true;
  518. }
  519. addItemAndSubItemsToArrayOfAllItems(item);
  520. item[this._rootItemPropName]=true;
  521. }
  522. // Step 2: Walk through all the attribute values of all the items,
  523. // and replace single values with arrays. For example, we change this:
  524. // { name:'Miss Piggy', pets:'Foo-Foo'}
  525. // into this:
  526. // { name:['Miss Piggy'], pets:['Foo-Foo']}
  527. //
  528. // We also store the attribute names so we can validate our store
  529. // reference and item id special properties for the O(1) isItem
  530. var allAttributeNames = {},
  531. key;
  532. for(i = 0; i < this._arrayOfAllItems.length; ++i){
  533. item = this._arrayOfAllItems[i];
  534. for(key in item){
  535. if(key !== this._rootItemPropName){
  536. var value = item[key];
  537. if(value !== null){
  538. if(!dojo.isArray(value)){
  539. item[key] = [value];
  540. }
  541. }else{
  542. item[key] = [null];
  543. }
  544. }
  545. allAttributeNames[key]=key;
  546. }
  547. }
  548. // Step 3: Build unique property names to use for the _storeRefPropName and _itemNumPropName
  549. // This should go really fast, it will generally never even run the loop.
  550. while(allAttributeNames[this._storeRefPropName]){
  551. this._storeRefPropName += "_";
  552. }
  553. while(allAttributeNames[this._itemNumPropName]){
  554. this._itemNumPropName += "_";
  555. }
  556. while(allAttributeNames[this._reverseRefMap]){
  557. this._reverseRefMap += "_";
  558. }
  559. // Step 4: Some data files specify an optional 'identifier', which is
  560. // the name of an attribute that holds the identity of each item.
  561. // If this data file specified an identifier attribute, then build a
  562. // hash table of items keyed by the identity of the items.
  563. var arrayOfValues;
  564. var identifier = dataObject.identifier;
  565. if(identifier){
  566. this._itemsByIdentity = {};
  567. this._features['dojo.data.api.Identity'] = identifier;
  568. for(i = 0; i < this._arrayOfAllItems.length; ++i){
  569. item = this._arrayOfAllItems[i];
  570. arrayOfValues = item[identifier];
  571. var identity = arrayOfValues[0];
  572. if(!Object.hasOwnProperty.call(this._itemsByIdentity, identity)){
  573. this._itemsByIdentity[identity] = item;
  574. }else{
  575. if(this._jsonFileUrl){
  576. throw new Error("dojo.data.ItemFileReadStore: The json data as specified by: [" + this._jsonFileUrl + "] is malformed. Items within the list have identifier: [" + identifier + "]. Value collided: [" + identity + "]");
  577. }else if(this._jsonData){
  578. throw new Error("dojo.data.ItemFileReadStore: The json data provided by the creation arguments is malformed. Items within the list have identifier: [" + identifier + "]. Value collided: [" + identity + "]");
  579. }
  580. }
  581. }
  582. }else{
  583. this._features['dojo.data.api.Identity'] = Number;
  584. }
  585. // Step 5: Walk through all the items, and set each item's properties
  586. // for _storeRefPropName and _itemNumPropName, so that store.isItem() will return true.
  587. for(i = 0; i < this._arrayOfAllItems.length; ++i){
  588. item = this._arrayOfAllItems[i];
  589. item[this._storeRefPropName] = this;
  590. item[this._itemNumPropName] = i;
  591. }
  592. // Step 6: We walk through all the attribute values of all the items,
  593. // looking for type/value literals and item-references.
  594. //
  595. // We replace item-references with pointers to items. For example, we change:
  596. // { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
  597. // into this:
  598. // { name:['Kermit'], friends:[miss_piggy] }
  599. // (where miss_piggy is the object representing the 'Miss Piggy' item).
  600. //
  601. // We replace type/value pairs with typed-literals. For example, we change:
  602. // { name:['Nelson Mandela'], born:[{_type:'Date', _value:'1918-07-18'}] }
  603. // into this:
  604. // { name:['Kermit'], born:(new Date(1918, 6, 18)) }
  605. //
  606. // We also generate the associate map for all items for the O(1) isItem function.
  607. for(i = 0; i < this._arrayOfAllItems.length; ++i){
  608. item = this._arrayOfAllItems[i]; // example: { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
  609. for(key in item){
  610. arrayOfValues = item[key]; // example: [{_reference:{name:'Miss Piggy'}}]
  611. for(var j = 0; j < arrayOfValues.length; ++j){
  612. value = arrayOfValues[j]; // example: {_reference:{name:'Miss Piggy'}}
  613. if(value !== null && typeof value == "object"){
  614. if(("_type" in value) && ("_value" in value)){
  615. var type = value._type; // examples: 'Date', 'Color', or 'ComplexNumber'
  616. var mappingObj = this._datatypeMap[type]; // examples: Date, dojo.Color, foo.math.ComplexNumber, {type: dojo.Color, deserialize(value){ return new dojo.Color(value)}}
  617. if(!mappingObj){
  618. throw new Error("dojo.data.ItemFileReadStore: in the typeMap constructor arg, no object class was specified for the datatype '" + type + "'");
  619. }else if(dojo.isFunction(mappingObj)){
  620. arrayOfValues[j] = new mappingObj(value._value);
  621. }else if(dojo.isFunction(mappingObj.deserialize)){
  622. arrayOfValues[j] = mappingObj.deserialize(value._value);
  623. }else{
  624. throw new Error("dojo.data.ItemFileReadStore: Value provided in typeMap was neither a constructor, nor a an object with a deserialize function");
  625. }
  626. }
  627. if(value._reference){
  628. var referenceDescription = value._reference; // example: {name:'Miss Piggy'}
  629. if(!dojo.isObject(referenceDescription)){
  630. // example: 'Miss Piggy'
  631. // from an item like: { name:['Kermit'], friends:[{_reference:'Miss Piggy'}]}
  632. arrayOfValues[j] = this._getItemByIdentity(referenceDescription);
  633. }else{
  634. // example: {name:'Miss Piggy'}
  635. // from an item like: { name:['Kermit'], friends:[{_reference:{name:'Miss Piggy'}}] }
  636. for(var k = 0; k < this._arrayOfAllItems.length; ++k){
  637. var candidateItem = this._arrayOfAllItems[k],
  638. found = true;
  639. for(var refKey in referenceDescription){
  640. if(candidateItem[refKey] != referenceDescription[refKey]){
  641. found = false;
  642. }
  643. }
  644. if(found){
  645. arrayOfValues[j] = candidateItem;
  646. }
  647. }
  648. }
  649. if(this.referenceIntegrity){
  650. var refItem = arrayOfValues[j];
  651. if(this.isItem(refItem)){
  652. this._addReferenceToMap(refItem, item, key);
  653. }
  654. }
  655. }else if(this.isItem(value)){
  656. //It's a child item (not one referenced through _reference).
  657. //We need to treat this as a referenced item, so it can be cleaned up
  658. //in a write store easily.
  659. if(this.referenceIntegrity){
  660. this._addReferenceToMap(value, item, key);
  661. }
  662. }
  663. }
  664. }
  665. }
  666. }
  667. },
  668. _addReferenceToMap: function(/*item*/ refItem, /*item*/ parentItem, /*string*/ attribute){
  669. // summary:
  670. // Method to add an reference map entry for an item and attribute.
  671. // description:
  672. // Method to add an reference map entry for an item and attribute. //
  673. // refItem:
  674. // The item that is referenced.
  675. // parentItem:
  676. // The item that holds the new reference to refItem.
  677. // attribute:
  678. // The attribute on parentItem that contains the new reference.
  679. //Stub function, does nothing. Real processing is in ItemFileWriteStore.
  680. },
  681. getIdentity: function(/* item */ item){
  682. // summary:
  683. // See dojo.data.api.Identity.getIdentity()
  684. var identifier = this._features['dojo.data.api.Identity'];
  685. if(identifier === Number){
  686. return item[this._itemNumPropName]; // Number
  687. }else{
  688. var arrayOfValues = item[identifier];
  689. if(arrayOfValues){
  690. return arrayOfValues[0]; // Object || String
  691. }
  692. }
  693. return null; // null
  694. },
  695. fetchItemByIdentity: function(/* Object */ keywordArgs){
  696. // summary:
  697. // See dojo.data.api.Identity.fetchItemByIdentity()
  698. // Hasn't loaded yet, we have to trigger the load.
  699. var item,
  700. scope;
  701. if(!this._loadFinished){
  702. var self = this;
  703. //Do a check on the JsonFileUrl and crosscheck it.
  704. //If it doesn't match the cross-check, it needs to be updated
  705. //This allows for either url or _jsonFileUrl to he changed to
  706. //reset the store load location. Done this way for backwards
  707. //compatibility. People use _jsonFileUrl (even though officially
  708. //private.
  709. if(this._jsonFileUrl !== this._ccUrl){
  710. dojo.deprecated("dojo.data.ItemFileReadStore: ",
  711. "To change the url, set the url property of the store," +
  712. " not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
  713. this._ccUrl = this._jsonFileUrl;
  714. this.url = this._jsonFileUrl;
  715. }else if(this.url !== this._ccUrl){
  716. this._jsonFileUrl = this.url;
  717. this._ccUrl = this.url;
  718. }
  719. //See if there was any forced reset of data.
  720. if(this.data != null && this._jsonData == null){
  721. this._jsonData = this.data;
  722. this.data = null;
  723. }
  724. if(this._jsonFileUrl){
  725. if(this._loadInProgress){
  726. this._queuedFetches.push({args: keywordArgs});
  727. }else{
  728. this._loadInProgress = true;
  729. var getArgs = {
  730. url: self._jsonFileUrl,
  731. handleAs: "json-comment-optional",
  732. preventCache: this.urlPreventCache,
  733. failOk: this.failOk
  734. };
  735. var getHandler = dojo.xhrGet(getArgs);
  736. getHandler.addCallback(function(data){
  737. var scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
  738. try{
  739. self._getItemsFromLoadedData(data);
  740. self._loadFinished = true;
  741. self._loadInProgress = false;
  742. item = self._getItemByIdentity(keywordArgs.identity);
  743. if(keywordArgs.onItem){
  744. keywordArgs.onItem.call(scope, item);
  745. }
  746. self._handleQueuedFetches();
  747. }catch(error){
  748. self._loadInProgress = false;
  749. if(keywordArgs.onError){
  750. keywordArgs.onError.call(scope, error);
  751. }
  752. }
  753. });
  754. getHandler.addErrback(function(error){
  755. self._loadInProgress = false;
  756. if(keywordArgs.onError){
  757. var scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
  758. keywordArgs.onError.call(scope, error);
  759. }
  760. });
  761. }
  762. }else if(this._jsonData){
  763. // Passed in data, no need to xhr.
  764. self._getItemsFromLoadedData(self._jsonData);
  765. self._jsonData = null;
  766. self._loadFinished = true;
  767. item = self._getItemByIdentity(keywordArgs.identity);
  768. if(keywordArgs.onItem){
  769. scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
  770. keywordArgs.onItem.call(scope, item);
  771. }
  772. }
  773. }else{
  774. // Already loaded. We can just look it up and call back.
  775. item = this._getItemByIdentity(keywordArgs.identity);
  776. if(keywordArgs.onItem){
  777. scope = keywordArgs.scope?keywordArgs.scope:dojo.global;
  778. keywordArgs.onItem.call(scope, item);
  779. }
  780. }
  781. },
  782. _getItemByIdentity: function(/* Object */ identity){
  783. // summary:
  784. // Internal function to look an item up by its identity map.
  785. var item = null;
  786. if(this._itemsByIdentity &&
  787. Object.hasOwnProperty.call(this._itemsByIdentity, identity)){
  788. item = this._itemsByIdentity[identity];
  789. }else if (Object.hasOwnProperty.call(this._arrayOfAllItems, identity)){
  790. item = this._arrayOfAllItems[identity];
  791. }
  792. if(item === undefined){
  793. item = null;
  794. }
  795. return item; // Object
  796. },
  797. getIdentityAttributes: function(/* item */ item){
  798. // summary:
  799. // See dojo.data.api.Identity.getIdentityAttributes()
  800. var identifier = this._features['dojo.data.api.Identity'];
  801. if(identifier === Number){
  802. // If (identifier === Number) it means getIdentity() just returns
  803. // an integer item-number for each item. The dojo.data.api.Identity
  804. // spec says we need to return null if the identity is not composed
  805. // of attributes
  806. return null; // null
  807. }else{
  808. return [identifier]; // Array
  809. }
  810. },
  811. _forceLoad: function(){
  812. // summary:
  813. // Internal function to force a load of the store if it hasn't occurred yet. This is required
  814. // for specific functions to work properly.
  815. var self = this;
  816. //Do a check on the JsonFileUrl and crosscheck it.
  817. //If it doesn't match the cross-check, it needs to be updated
  818. //This allows for either url or _jsonFileUrl to he changed to
  819. //reset the store load location. Done this way for backwards
  820. //compatibility. People use _jsonFileUrl (even though officially
  821. //private.
  822. if(this._jsonFileUrl !== this._ccUrl){
  823. dojo.deprecated("dojo.data.ItemFileReadStore: ",
  824. "To change the url, set the url property of the store," +
  825. " not _jsonFileUrl. _jsonFileUrl support will be removed in 2.0");
  826. this._ccUrl = this._jsonFileUrl;
  827. this.url = this._jsonFileUrl;
  828. }else if(this.url !== this._ccUrl){
  829. this._jsonFileUrl = this.url;
  830. this._ccUrl = this.url;
  831. }
  832. //See if there was any forced reset of data.
  833. if(this.data != null){
  834. this._jsonData = this.data;
  835. this.data = null;
  836. }
  837. if(this._jsonFileUrl){
  838. var getArgs = {
  839. url: this._jsonFileUrl,
  840. handleAs: "json-comment-optional",
  841. preventCache: this.urlPreventCache,
  842. failOk: this.failOk,
  843. sync: true
  844. };
  845. var getHandler = dojo.xhrGet(getArgs);
  846. getHandler.addCallback(function(data){
  847. try{
  848. //Check to be sure there wasn't another load going on concurrently
  849. //So we don't clobber data that comes in on it. If there is a load going on
  850. //then do not save this data. It will potentially clobber current data.
  851. //We mainly wanted to sync/wait here.
  852. //TODO: Revisit the loading scheme of this store to improve multi-initial
  853. //request handling.
  854. if(self._loadInProgress !== true && !self._loadFinished){
  855. self._getItemsFromLoadedData(data);
  856. self._loadFinished = true;
  857. }else if(self._loadInProgress){
  858. //Okay, we hit an error state we can't recover from. A forced load occurred
  859. //while an async load was occurring. Since we cannot block at this point, the best
  860. //that can be managed is to throw an error.
  861. throw new Error("dojo.data.ItemFileReadStore: Unable to perform a synchronous load, an async load is in progress.");
  862. }
  863. }catch(e){
  864. console.log(e);
  865. throw e;
  866. }
  867. });
  868. getHandler.addErrback(function(error){
  869. throw error;
  870. });
  871. }else if(this._jsonData){
  872. self._getItemsFromLoadedData(self._jsonData);
  873. self._jsonData = null;
  874. self._loadFinished = true;
  875. }
  876. }
  877. });
  878. //Mix in the simple fetch implementation to this class.
  879. dojo.extend(dojo.data.ItemFileReadStore,dojo.data.util.simpleFetch);
  880. }