Created
July 3, 2014 05:57
-
-
Save ianmstew/1efac97a2cd519c0b722 to your computer and use it in GitHub Desktop.
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
/* | |
* So, your json from here http://screencast.com/t/zv8sQGVk6 is organized like this: | |
* array (roles) -> model (role) -> array (permissions) -> model (permission). Collections | |
* already handle array -> model by design. What you need to add is a model that contains a | |
* collection; in other words, the role model should contain a permission collection. | |
* That's what this file is :) | |
*/ | |
var RoleModel = Backbone.Model.extend({ | |
// See http://backbonejs.org/#Model-parse | |
// See backbone.js source code for Model.parse()--it's a simple return | |
parse: function (response, options) { | |
// 'response' is the literal json object from fetch() or sync() operations. | |
// We need to replace the nested permissions json array with an actual collection. | |
if (response.permissions) { | |
response.permissions = new PermissionCollection(response.permissions); | |
} | |
return response; | |
}, | |
// See http://backbonejs.org/#Model-toJSON | |
// See backbone.js source code for Model.toJSON()--it's a simple shallow clone | |
toJSON: function () { | |
// Shallow clone of attributes--taken from backbone.js source for toJSON() | |
var attributes = _.clone(this.attributes); | |
// Since parse() turned permissions into a collection, we need to turn it back into JSON here. | |
// The clone is ideal so that someone holding the toJSON result can't accidentally change the | |
// contents of the collection. | |
// See http://backbonejs.org/#Collection-models | |
// See http://stackoverflow.com/a/21003060/957813 | |
attributes.permissions = _.map(attributes.permissions.models, _.clone); | |
return attributes; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment