Created
December 17, 2014 16:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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