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 + }); +}]);