Skip to content

Instantly share code, notes, and snippets.

@dreadjr
Forked from katowulf/normalize_record.js
Last active August 29, 2015 14:19
Show Gist options
  • Save dreadjr/107b03295ad363c3d293 to your computer and use it in GitHub Desktop.
Save dreadjr/107b03295ad363c3d293 to your computer and use it in GitHub Desktop.
app.factory('NormalizedPosts', function($FirebaseArray, userCache) {
var PostsWithUsers = $FirebaseArray.$extendFactory({
// override $$added to include users
$$added: function(snap) {
// call the super method
var record = $FirebaseArray.prototype.$$added.call(this, snap);
userCache.$load( record.user ).$loaded(function( userData ) {
record.userData = userData;
});
// return the modified record
return record;
}
});
return PostsWithUsers;
});
app.factory('userCache', function ($firebase) {
return function (ref) {
var cachedUsers = {};
// loads one user into the local cache, you do not need to
// wait for this to show it in your view, Angular and Firebase
// will work out the details in the background
cachedUsers.$load = function (id) {
if( !cachedUsers.hasOwnProperty(id) ) {
cachedUsers[id] = $firebase(ref.child(id)).$asObject();
}
return cachedUsers[id];
};
// frees memory and stops listening on user objects
// use this when you switch views in your SPA and no longer
// need this list
cachedUsers.$dispose = function () {
angular.forEach(cachedUsers, function (user) {
user.$destroy();
});
};
// removes one user, note that the user does not have
// to be cached locally for this to work
cachedUsers.$remove = function(id) {
delete cachedUsers[id];
ref.child(id).remove();
};
return cachedUsers;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment