Skip to content

Instantly share code, notes, and snippets.

@dengue8830
Last active January 8, 2017 00:28
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 dengue8830/11a16546d8b979e34daf62a5471c9183 to your computer and use it in GitHub Desktop.
Save dengue8830/11a16546d8b979e34daf62a5471c9183 to your computer and use it in GitHub Desktop.
Whitelist function for the backbone base model. This allows me to select which attributes i want to send to the server or something else
//Define the base model
var BaseModel = Backbone.Model.extend({
toJSON: function(options) {
options = options || {};
var json;
if(!!options.whiteList)
json = _.pick(this.attributes, options.whiteList);
else if(!!options.blackList)
json = _.omit(this.attributes, options.blackList);
else
json = _.clone(this.attributes);
for(var attr in json) {
if((json[attr] instanceof app.models.BaseModel) || (json[attr] instanceof app.collections.BaseCollection)) {
json[attr] = json[attr].toJSON(options[attr]);
}
}
return json;
}
});
//you can extend the base model to a Person model for example
var Person = BaseModel.extend(/*...*/);
/*Example of usage*/
var aPerson = new Person();
//populate the model...
//get the filtered json version
var jsonVersion = aPerson.toJSON({
whiteList: ['countries', 'firstName', 'type', 'id'],
countries: {
city: {whiteList: ['id', 'cid', 'name']},
people: {blackList: ['cid']}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment