Skip to content

Instantly share code, notes, and snippets.

@runeb
Created November 23, 2011 15:55
Show Gist options
  • Save runeb/1389040 to your computer and use it in GitHub Desktop.
Save runeb/1389040 to your computer and use it in GitHub Desktop.
Backbone support for (railsy) namespaces in model/collection json representations
// 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;
});
}
});
@narcisoguillen
Copy link

How about ?

 _.extend(Backbone.Model.prototype,{
   parse : function(response, options) {
      return response[this.namespace] || response;
  }
});

and

 _.extend(Backbone.Collection.prototype,{
   parse : function(response, xhr) {
     response[this.namespace] || (response = response[this.namespace]);

     return _.map(response, function(attrs) {
       var model = new this.model();
       model.set(model.parse(attrs));
       return model;
     }, this);
   }
 });

@Lordnibbler
Copy link

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