Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for multiple model types to shared.js #343

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 45 additions & 14 deletions src/plugins/shared.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
}]);
});
}]);