Last active
January 8, 2017 00:28
-
-
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
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
//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