Backbone-Relationalまたはsupermodel.jsをご覧ください。
これらのプロジェクトは、デフォルトの実装よりも優れた形式のモデルネストを提供します。
次のようなバックボーンモデルをネストします。
var MyModel = Backbone.Model.extend({});
var MySubModel = Backbone.Model.extend({});
var model = new MyModel({submodel: new MySubModel({color: 'blue'})});
そして、toJSON
メソッドをオーバーライドします。
// nested models! Might just override the internal representation of this...
_.extend(Backbone.Model.prototype, {
// Version of toJSON that traverses nested models
toJSON: function() {
var obj = _.clone(this.attributes);
_.each(_.keys(obj), function(key) {
if(!_.isUndefined(obj[key]) && !_.isNull(obj[key]) && _.isFunction(obj[key].toJSON)) {
obj[key] = obj[key].toJSON();
}
});
return obj;
}
});
_.extend(Backbone.Collection.prototype, {
// Version of toJSON that traverses nested models
toJSON: function() {
return this.map(function(model){ return model.toJSON(); });
}
});
したがって、モデルをネストすると、JSON表現は正しく表示されます。ただし、モデルのメソッドに注意を払う必要がありparse
ます。サーバーからJSONを取得する場合、すべてが正しく機能するためには、そこにすべてのサブモデルとコレクションを生成する必要があります。