我是Backbone的新手。
是否可以在骨干中定义一个模型,其中包含相同类型的模型列表?例如:
MyModel = Backbone.Model.extend({
initialize: function() {
nestedMyModels:new Array();
},
addMyModel: function(aModel) {
// Code here would push() aModel onto array
},
render: function() {
// Loop through array calling render() recursively
}
});
然后我会有一个View开始递归调用render()。例如:
MyView = Backbone.View.extend({
render:function() {
this.model.render();
}
});
答案 0 :(得分:3)
您始终认为,在Array
中,Backbone中Models
Collection
的人认为。
现在你需要做的是实现 MyModels 的集合,并在 MyModel 实例中保留它的一个实例。
// code simplified and not tested
MyModel = Backbone.Model.extend({
initialize: function() {
this.nestedMyModels: new MyModels();
},
addMyModel: function( model ) {
this.nestedMyModels.add( model );
}
});
MyModels = Backbone.Collection.extend({
model: MyModel
});
您始终认为render
在View
中思考。
建议的方法是,如果您有Collection
和Model
,每个人的View
更好。这样,集合视图将在迭代中调用模型视图:
// code simplified and not tested
MyModelView = Backbone.View.extend({
render: function(){
this.$el.html( model.get("name") );
var view = new MyModelsView({ collection: this.model.nestedMyModels });
this.$el.append( view.render.el );
return this;
}
});
MyModelsView = Backbone.View.extend({
render: function(){
this.collection.each( function( model ){
var view = new MyModelView({ model: model });
this.$el.append( view.render.el );
});
return this;
}
});
答案 1 :(得分:0)
你想要的是collection。它基本上是一个列表或模型数组。
答案 2 :(得分:0)
集合是有序的模型集。有关更多信息,请查看。 http://backbonejs.org/#Collection
以下是一个例子:
var Library = Backbone.Collection.extend({
model: Book
});
答案 3 :(得分:0)
是否可以在骨干中定义包含列表的模型 相同类型的型号?
当然,为什么不呢。
var MyModel = Nested.Model.extend();
MyModel.define({
defaults : {
nestedMyModels : MyModel.Collection
},
addMyModel: function( model ) {
this.nestedMyModels.add( model );
}
});
不在香草骨干中。你需要一个插件。 https://github.com/Volicon/backbone.nestedTypes
PS:正如其他回复中提到的那样,你需要使用View来渲染东西。不是模特。