Skip to content

Instantly share code, notes, and snippets.

@menacestudio
Last active December 14, 2015 19:49
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 menacestudio/5139389 to your computer and use it in GitHub Desktop.
Save menacestudio/5139389 to your computer and use it in GitHub Desktop.
Backbone: Only persist a Model with valid attributes.
var President = Backbone.Model.extend({});
var m = new President({first: 'Abraham', last: 'Lincoln', age: 90, registered: true});
m.set({first: null});
/** Loop through each property and unset if invalid. Also check if property if boolean type. */
_.each(m.toJSON(), function(val, col){
if (typeof val !=='boolean' && !val) {
m.unset(col);
}
}, this);
console.log(m.toJSON());
var President = Backbone.Model.extend({});
var m = new President({first: 'Abraham', last: 'Lincoln', age: 90, registered: true});
m.set({first: null});
/** Pass changed attributes to a new Model */
var t = new President();
if (!_.isEmpty(m.changedAttributes())) {
_.each(m.changedAttributes(), function(val, col) {
t.set(col, val);
}, this);
}
console.log(t.toJSON());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment