Created
November 23, 2011 15:55
-
-
Save runeb/1389040 to your computer and use it in GitHub Desktop.
Backbone support for (railsy) namespaces in model/collection json representations
This file contains hidden or 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
// Extend Backbone.Model to support setting a namespace | |
// for models. Example response from server: | |
// { | |
// 'modelname' : { | |
// ... attributes ... | |
// } | |
// We dont want the attributes to be scoped by the model name | |
// in the models attributes property. This new parse function | |
// will drop the namespace if it is defined on the model. | |
// Example: | |
// | |
// SomeModel = Backbone.Model.extend({ | |
// namespace : 'someModel' | |
// }); | |
_.extend(Backbone.Model.prototype,{ | |
parse : function(resp, xhr) { | |
var ns = this.namespace; | |
if(ns) { | |
return resp[ns]; | |
} | |
return resp; | |
} | |
}); | |
// Extend Backbone.Collection to support setting a namespace | |
// for the collection and its models. Example response from server: | |
// { | |
// 'models' : {[ | |
// 'model' : { | |
// ... attributes ... | |
// }]} | |
// | |
// We dont want the attributes to be scoped by the models root | |
// This new parse function will drop the namespace | |
// if it is defined on the collection. Example: | |
// | |
// SomeCollection = Backbone.Collection.extend({ | |
// namespace : 'myModels' | |
// }); | |
_.extend(Backbone.Collection.prototype,{ | |
parse : function(resp, xhr) { | |
var collection = this; | |
var ns = collection.namespace; | |
var result = resp; | |
if(ns) { | |
result = resp[ns]; | |
} | |
// Not sure how necessary this step is | |
return _.map(result, function(attrs) { | |
var model = new collection.model(); | |
model.set(model.parse(attrs)); | |
return model; | |
}); | |
} | |
}); |
That didn't quite work -- updated here:
_.extend(Backbone.Model.prototype,{
parse : function(response, options) {
return response[this.namespace] || response;
}
});
_.extend(Backbone.Collection.prototype,{
parse : function(resp, xhr) {
resp = resp[this.namespace] || resp;
return _.map(resp, function(attrs){
var model = new this.model();
model.set(model.parse(attrs));
return model;
}, this);
}
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How about ?
and