[Persistence] Reuse instances in cache

Reuse/update a single object instance in the persistence
cache, such that updates can be trivially reflected
everywhere. WTD-791.
This commit is contained in:
Victor Woeltjen 2015-02-02 10:00:50 -08:00
parent 2a11204ee6
commit 014fca0494

View File

@ -21,10 +21,38 @@ define(
var spaces = CACHE_SPACES || [], // List of spaces to cache
cache = {}; // Where objects will be stored
// Update the cached instance of an object to a new value
function replaceValue(valueHolder, newValue) {
var v = valueHolder.value;
// If it's a JS object, we want to replace contents, so that
// everybody gets the same instance.
if (typeof v === 'object' && v !== null) {
// Only update contents if these are different instances
if (v !== newValue) {
// Clear prior contents
Object.keys(v).forEach(function (k) {
delete v[k];
});
// Shallow-copy contents
Object.keys(newValue).forEach(function (k) {
v[k] = newValue[k];
});
}
} else {
// Otherwise, just store the new value
valueHolder.value = newValue;
}
}
// Place value in the cache for space, if there is one.
function addToCache(space, key, value) {
if (cache[space]) {
cache[space][key] = { value: value };
if (cache[space][key]) {
replaceValue(cache[space][key], value);
} else {
cache[space][key] = { value: value };
}
}
}