From e47fecf97aff365f0a82cce1c523c4df2ac3ce4d Mon Sep 17 00:00:00 2001 From: Luke DeBoer Date: Sat, 24 Oct 2015 12:51:03 -0400 Subject: [PATCH] Added support for multiple model types to shared.js Allows shared.js to store cache based on type of data, so it can store multiple objects with the same $pk, as long as they are of different types. Most of this code came from @jasonayre in issue #208. Lines 39-41 were added by me to fix a bug where model scopes would get nested after being cached. This way the scope is refreshed every time it is read from the cache. --- src/plugins/shared.js | 59 +++++++++++++++++++++++++++++++++---------- 1 file changed, 45 insertions(+), 14 deletions(-) diff --git a/src/plugins/shared.js b/src/plugins/shared.js index 6ac10c7..ddc8572 100644 --- a/src/plugins/shared.js +++ b/src/plugins/shared.js @@ -9,25 +9,56 @@ 'use strict'; angular.module('restmod').factory('SharedModel', ['restmod', function(restmod) { - return restmod.mixin(function() { - - var cache = {}; // keep one cache instance per type + return restmod.mixin({ + $extend : { + Model: { + cache: {}, + } + } + }, function() { this - // override scope.$new to return existing instances or update cache. + // this will cache record by its type within cache, as apparently cache + // variable as assigned above will be shared between models + .define('Model.$cache', function(){ + var self = this; + + if(self.cache.hasOwnProperty(self.identity())) { + return self.cache[self.identity()]; + } else { + return self.cache[self.identity()] = {}; + } + }) .define('Model.$new', function(_key, _scope) { + var self = this; + if(_key) { // search for instance with same key, if key is found then return instance - return cache[_key] || (cache[_key] = this.$super(_key, _scope)); - } + if(self.$cache().hasOwnProperty(_key)) { + var cached = self.$cache()[_key]; + if(typeof _scope == 'object'){ + cached.$scope = _scope; + } + return cached; + } else { + return (self.$cache()[_key] = this.$super(_key, _scope)); + } + } else { - return this.$super(_key, _scope); + return this.$super(_key, _scope); + } }) - // override record.$decode to update cache on decoding. - .define('$decode', function(_raw, _mask) { - var result = this.$super(_raw, _mask); - if(result.$pk) cache[result.$pk] = this; // cache instance if $pk becomes available. - return result; + + // override $decode to update cache on decoding. + .define('Model.$decode', function(_raw, _mask) { + var self = this, + result = this.$super(_raw, _mask); + + if(result.$pk) { + self.$cache()[result.$pk] = this; + } + + return this.$super(_raw, _mask); }); - }); -}]); \ No newline at end of file + }); +}]);