Skip to content

Instantly share code, notes, and snippets.

@katowulf
Created December 17, 2014 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katowulf/d0c230f1a7f6b5806a29 to your computer and use it in GitHub Desktop.
Save katowulf/d0c230f1a7f6b5806a29 to your computer and use it in GitHub Desktop.
Override AngularFire's $save method to do an update, if a list of fields is provided.
var SmartSaveFactory = $FirebaseArray.$extendFactory({
$save: function(indexOrItem, listOfFields) {
if( !listOfFields ) {
// do a normal save if no list of fields is provided
return $FirebaseArray.prototype.$save.apply(this, arguments);
}
else {
// this is a bit risky since we're using an internal method that could change
// we could remove this coupling by always passing the item instead of allowing
// an index, which would prevent relying on a private method
var item = self._resolveItem(indexOrItem);
var key = self.$keyAt(item);
if( key !== null ) {
var updateFields = pickFields(item, listOfFields);
return self.$inst().$update(key, $firebaseUtils.toJSON(updateFields))
.then(function(ref) {
self.$$notify('child_changed', key);
return ref;
});
}
else {
return $firebaseUtils.reject('Invalid record; could determine its key: '+indexOrItem);
}
}
}
});
function pickFields(data, fields) {
var out = {};
angular.forEach(fields, function(k) {
out[k] = data.hasOwnProperty(k)? data[k] : null;
});
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment