Skip to content

Instantly share code, notes, and snippets.

@muraiki
Created March 19, 2015 18:54
Show Gist options
  • Save muraiki/96d746eff5f564c32990 to your computer and use it in GitHub Desktop.
Save muraiki/96d746eff5f564c32990 to your computer and use it in GitHub Desktop.
updating KO model from json
// map the keys in json to the properties on your model
var desiredKeys = {
"foo": "foo",
"bar": "bar"
};
Object.defineProperty(self, 'updateFromJson', {
enumerable: true,
value: function (data) {
Object.keys(data)
.forEach(function (key) {
var modelKey = desiredKeys[key];
if (!modelKey) return;
if ( !_.isEqual(self[modelKey], data[key]) )
self[modelKey] = data[key]; // I can use = syntax because I use Object.defineproperty with setters
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment