📄 itemfilewritestore.js
字号:
if(!dojo._hasResource["dojo.data.ItemFileWriteStore"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.dojo._hasResource["dojo.data.ItemFileWriteStore"] = true;dojo.provide("dojo.data.ItemFileWriteStore");dojo.require("dojo.data.ItemFileReadStore");dojo.declare("dojo.data.ItemFileWriteStore", dojo.data.ItemFileReadStore, { constructor: function(/* object */ keywordParameters){ // keywordParameters: {typeMap: object) // The structure of the typeMap object is as follows: // { // type0: function || object, // type1: function || object, // ... // typeN: function || object // } // Where if it is a function, it is assumed to be an object constructor that takes the // value of _value as the initialization parameters. It is serialized assuming object.toString() // serialization. If it is an object, then it is assumed // to be an object of general form: // { // type: function, //constructor. // deserialize: function(value) //The function that parses the value and constructs the object defined by type appropriately. // serialize: function(object) //The function that converts the object back into the proper file format form. // } // ItemFileWriteStore extends ItemFileReadStore to implement these additional dojo.data APIs this._features['dojo.data.api.Write'] = true; this._features['dojo.data.api.Notification'] = true; // For keeping track of changes so that we can implement isDirty and revert this._pending = { _newItems:{}, _modifiedItems:{}, _deletedItems:{} }; if(!this._datatypeMap['Date'].serialize){ this._datatypeMap['Date'].serialize = function(obj){ return dojo.date.stamp.toISOString(obj, {zulu:true}); }; } //Disable only if explicitly set to false. if(keywordParameters && (keywordParameters.referenceIntegrity === false)){ this.referenceIntegrity = false; } // this._saveInProgress is set to true, briefly, from when save() is first called to when it completes this._saveInProgress = false; }, referenceIntegrity: true, //Flag that defaultly enabled reference integrity tracking. This way it can also be disabled pogrammatially or declaratively. _assert: function(/* boolean */ condition){ if(!condition) { throw new Error("assertion failed in ItemFileWriteStore"); } }, _getIdentifierAttribute: function(){ var identifierAttribute = this.getFeatures()['dojo.data.api.Identity']; // this._assert((identifierAttribute === Number) || (dojo.isString(identifierAttribute))); return identifierAttribute; }, /* dojo.data.api.Write */ newItem: function(/* Object? */ keywordArgs, /* Object? */ parentInfo){ // summary: See dojo.data.api.Write.newItem() this._assert(!this._saveInProgress); if (!this._loadFinished){ // We need to do this here so that we'll be able to find out what // identifierAttribute was specified in the data file. this._forceLoad(); } if(typeof keywordArgs != "object" && typeof keywordArgs != "undefined"){ throw new Error("newItem() was passed something other than an object"); } var newIdentity = null; var identifierAttribute = this._getIdentifierAttribute(); if(identifierAttribute === Number){ newIdentity = this._arrayOfAllItems.length; }else{ newIdentity = keywordArgs[identifierAttribute]; if (typeof newIdentity === "undefined"){ throw new Error("newItem() was not passed an identity for the new item"); } if (dojo.isArray(newIdentity)){ throw new Error("newItem() was not passed an single-valued identity"); } } // make sure this identity is not already in use by another item, if identifiers were // defined in the file. Otherwise it would be the item count, // which should always be unique in this case. if(this._itemsByIdentity){ this._assert(typeof this._itemsByIdentity[newIdentity] === "undefined"); } this._assert(typeof this._pending._newItems[newIdentity] === "undefined"); this._assert(typeof this._pending._deletedItems[newIdentity] === "undefined"); var newItem = {}; newItem[this._storeRefPropName] = this; newItem[this._itemNumPropName] = this._arrayOfAllItems.length; if(this._itemsByIdentity){ this._itemsByIdentity[newIdentity] = newItem; //We have to set the identifier now, otherwise we can't look it //up at calls to setValueorValues in parentInfo handling. newItem[identifierAttribute] = [newIdentity]; } this._arrayOfAllItems.push(newItem); //We need to construct some data for the onNew call too... var pInfo = null; // Now we need to check to see where we want to assign this thingm if any. if(parentInfo && parentInfo.parent && parentInfo.attribute){ pInfo = { item: parentInfo.parent, attribute: parentInfo.attribute, oldValue: undefined }; //See if it is multi-valued or not and handle appropriately //Generally, all attributes are multi-valued for this store //So, we only need to append if there are already values present. var values = this.getValues(parentInfo.parent, parentInfo.attribute); if(values && values.length > 0){ var tempValues = values.slice(0, values.length); if(values.length === 1){ pInfo.oldValue = values[0]; }else{ pInfo.oldValue = values.slice(0, values.length); } tempValues.push(newItem); this._setValueOrValues(parentInfo.parent, parentInfo.attribute, tempValues, false); pInfo.newValue = this.getValues(parentInfo.parent, parentInfo.attribute); }else{ this._setValueOrValues(parentInfo.parent, parentInfo.attribute, newItem, false); pInfo.newValue = newItem; } }else{ //Toplevel item, add to both top list as well as all list. newItem[this._rootItemPropName]=true; this._arrayOfTopLevelItems.push(newItem); } this._pending._newItems[newIdentity] = newItem; //Clone over the properties to the new item for(var key in keywordArgs){ if(key === this._storeRefPropName || key === this._itemNumPropName){ // Bummer, the user is trying to do something like // newItem({_S:"foo"}). Unfortunately, our superclass, // ItemFileReadStore, is already using _S in each of our items // to hold private info. To avoid a naming collision, we // need to move all our private info to some other property // of all the items/objects. So, we need to iterate over all // the items and do something like: // item.__S = item._S; // item._S = undefined; // But first we have to make sure the new "__S" variable is // not in use, which means we have to iterate over all the // items checking for that. throw new Error("encountered bug in ItemFileWriteStore.newItem"); } var value = keywordArgs[key]; if(!dojo.isArray(value)){ value = [value]; } newItem[key] = value; if(this.referenceIntegrity){ for(var i = 0; i < value.length; i++){ var val = value[i]; if(this.isItem(val)){ this._addReferenceToMap(val, newItem, key); } } } } this.onNew(newItem, pInfo); // dojo.data.api.Notification call return newItem; // item }, _removeArrayElement: function(/* Array */ array, /* anything */ element){ var index = dojo.indexOf(array, element); if (index != -1){ array.splice(index, 1); return true; } return false; }, deleteItem: function(/* item */ item){ // summary: See dojo.data.api.Write.deleteItem() this._assert(!this._saveInProgress); this._assertIsItem(item); // Remove this item from the _arrayOfAllItems, but leave a null value in place // of the item, so as not to change the length of the array, so that in newItem() // we can still safely do: newIdentity = this._arrayOfAllItems.length; var indexInArrayOfAllItems = item[this._itemNumPropName]; var identity = this.getIdentity(item); //If we have reference integrity on, we need to do reference cleanup for the deleted item if(this.referenceIntegrity){ //First scan all the attributes of this items for references and clean them up in the map //As this item is going away, no need to track its references anymore. //Get the attributes list before we generate the backup so it //doesn't pollute the attributes list. var attributes = this.getAttributes(item); //Backup the map, we'll have to restore it potentially, in a revert. if(item[this._reverseRefMap]){ item["backup_" + this._reverseRefMap] = dojo.clone(item[this._reverseRefMap]); } //TODO: This causes a reversion problem. This list won't be restored on revert since it is //attached to the 'value'. item, not ours. Need to back tese up somehow too. //Maybe build a map of the backup of the entries and attach it to the deleted item to be restored //later. Or just record them and call _addReferenceToMap on them in revert. dojo.forEach(attributes, function(attribute){ dojo.forEach(this.getValues(item, attribute), function(value){ if(this.isItem(value)){ //We have to back up all the references we had to others so they can be restored on a revert. if(!item["backupRefs_" + this._reverseRefMap]){ item["backupRefs_" + this._reverseRefMap] = []; } item["backupRefs_" + this._reverseRefMap].push({id: this.getIdentity(value), attr: attribute}); this._removeReferenceFromMap(value, item, attribute); } }, this); }, this); //Next, see if we have references to this item, if we do, we have to clean them up too. var references = item[this._reverseRefMap]; if(references){ //Look through all the items noted as references to clean them up. for(var itemId in references){ var containingItem = null; if(this._itemsByIdentity){ containingItem = this._itemsByIdentity[itemId]; }else{ containingItem = this._arrayOfAllItems[itemId]; } //We have a reference to a containing item, now we have to process the //attributes and clear all references to the item being deleted. if(containingItem){ for(var attribute in references[itemId]){ var oldValues = this.getValues(containingItem, attribute) || []; var newValues = dojo.filter(oldValues, function(possibleItem){ return !(this.isItem(possibleItem) && this.getIdentity(possibleItem) == identity); }, this); //Remove the note of the reference to the item and set the values on the modified attribute. this._removeReferenceFromMap(item, containingItem, attribute); if(newValues.length < oldValues.length){ this.setValues(containingItem, attribute, newValues); } } } } } } this._arrayOfAllItems[indexInArrayOfAllItems] = null; item[this._storeRefPropName] = null; if(this._itemsByIdentity){ delete this._itemsByIdentity[identity]; } this._pending._deletedItems[identity] = item; //Remove from the toplevel items, if necessary... if(item[this._rootItemPropName]){ this._removeArrayElement(this._arrayOfTopLevelItems, item); } this.onDelete(item); // dojo.data.api.Notification call return true; }, setValue: function(/* item */ item, /* attribute-name-string */ attribute, /* almost anything */ value){ // summary: See dojo.data.api.Write.set() return this._setValueOrValues(item, attribute, value, true); // boolean }, setValues: function(/* item */ item, /* attribute-name-string */ attribute, /* array */ values){ // summary: See dojo.data.api.Write.setValues() return this._setValueOrValues(item, attribute, values, true); // boolean }, unsetAttribute: function(/* item */ item, /* attribute-name-string */ attribute){ // summary: See dojo.data.api.Write.unsetAttribute() return this._setValueOrValues(item, attribute, [], true); }, _setValueOrValues: function(/* item */ item, /* attribute-name-string */ attribute, /* anything */ newValueOrValues, /*boolean?*/ callOnSet){ this._assert(!this._saveInProgress); // Check for valid arguments this._assertIsItem(item); this._assert(dojo.isString(attribute)); this._assert(typeof newValueOrValues !== "undefined"); // Make sure the user isn't trying to change the item's identity var identifierAttribute = this._getIdentifierAttribute(); if(attribute == identifierAttribute){ throw new Error("ItemFileWriteStore does not have support for changing the value of an item's identifier."); } // To implement the Notification API, we need to make a note of what // the old attribute value was, so that we can pass that info when // we call the onSet method. var oldValueOrValues = this._getValueOrValues(item, attribute); var identity = this.getIdentity(item); if(!this._pending._modifiedItems[identity]){ // Before we actually change the item, we make a copy of it to // record the original state, so that we'll be able to revert if // the revert method gets called. If the item has already been // modified then there's no need to do this now, since we already // have a record of the original state. var copyOfItemState = {}; for(var key in item){ if((key === this._storeRefPropName) || (key === this._itemNumPropName) || (key === this._rootItemPropName)){ copyOfItemState[key] = item[key]; }else if(key === this._reverseRefMap){ copyOfItemState[key] = dojo.clone(item[key]); }else{ copyOfItemState[key] = item[key].slice(0, item[key].length); } } // Now mark the item as dirty, and save the copy of the original state this._pending._modifiedItems[identity] = copyOfItemState; } // Okay, now we can actually change this attribute on the item var success = false; if(dojo.isArray(newValueOrValues) && newValueOrValues.length === 0){ // If we were passed an empty array as the value, that counts // as "unsetting" the attribute, so we need to remove this // attribute from the item. success = delete item[attribute]; newValueOrValues = undefined; // used in the onSet Notification call below if(this.referenceIntegrity && oldValueOrValues){ var oldValues = oldValueOrValues; if (!dojo.isArray(oldValues)){ oldValues = [oldValues]; } for(var i = 0; i < oldValues.length; i++){ var value = oldValues[i]; if(this.isItem(value)){ this._removeReferenceFromMap(value, item, attribute); } } } }else{ var newValueArray; if(dojo.isArray(newValueOrValues)){ var newValues = newValueOrValues; // Unfortunately, it's not safe to just do this: // newValueArray = newValues; // Instead, we need to copy the array, which slice() does very nicely. // This is so that our internal data structure won't // get corrupted if the user mucks with the values array *after* // calling setValues(). newValueArray = newValueOrValues.slice(0, newValueOrValues.length); }else{ newValueArray = [newValueOrValues]; } //We need to handle reference integrity if this is on. //In the case of set, we need to see if references were added or removed //and update the reference tracking map accordingly. if(this.referenceIntegrity){ if(oldValueOrValues){ var oldValues = oldValueOrValues; if(!dojo.isArray(oldValues)){ oldValues = [oldValues]; } //Use an associative map to determine what was added/removed from the list. //Should be O(n) performant. First look at all the old values and make a list of them //Then for any item not in the old list, we add it. If it was already present, we remove it. //Then we pass over the map and any references left it it need to be removed (IE, no match in //the new values list). var map = {}; dojo.forEach(oldValues, function(possibleItem){ if(this.isItem(possibleItem)){ var id = this.getIdentity(possibleItem); map[id.toString()] = true; } }, this); dojo.forEach(newValueArray, function(possibleItem){ if(this.isItem(possibleItem)){ var id = this.getIdentity(possibleItem); if(map[id.toString()]){ delete map[id.toString()];
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -