5

I have a Backbone Model that contains a collection:

var Stream =  Backbone.Model.extend({
    defaults: {
        dummyField: "1",
        excludedUsers: new Backbone.Collection()
    }
});

var s = new Stream;
s.get('excludedUsers').add( {name:'Stefan'} );
console.log(s.toJSON())

yields:

{ dummyField: '1',
  excludedUsers: 
   { length: 1,
     models: [ [Object] ],
     _byId: {},
     _byCid: { c1: [Object] } } }

instead of the "expected":

 { 
      dummyField: '1',
      excludedUsers: [ {name:'Stefan'} ]
 }

because Backbone isn't deeply JSONing the Model. The only way of working around is to override the toJSON method on the Stream's prototype but that won't help for other cases. Is there a general/better solution (besides the heavy Backbone.Relational plugin) already?

4

2 回答 2

0

您可能希望Backbone.Collection.toJSON()直接覆盖该函数或创建一个新集合,将所有其他集合扩展到其中:

var MyDefaultCollection = Backbone.Collection.extend({
    toJSON: function() {
        //Your code here
    }
});
var Stream = Backbone.Model.extend({
    defaults: {
        dummyField: "1",
        excludedUsers: new MyDefaultCollection()
    }
});
//You could also extend it
var NewCollection = MyDefaultCollection.extend({
    //custom code here
});

这只是理论,我从未编写过代码,因此欢迎对我的想法提出任何反馈:)

于 2012-10-18T15:00:54.787 回答
0
function flattenModel(model) {
    return _.mapValues(model.attributes, flatten);
}

function flattenCollection(collection) {
    return collection.map(flattenModel);
}

function flatten(object) {
    if (object instanceof Backbone.Model) {
        return flattenModel(object);
    } else if (object instanceof Backbone.Collection) {
        return flattenCollection(object);
    }

    return object;
}

这将返回一个对象,然后:

JSON.stringify(flatten(model))

请注意, _. mapValues是 lodash 提供的一个方便的方法,因此您应该使用该方法或仅​​移植该方法。

于 2015-11-11T12:07:14.920 回答