Nested models of the same 'class' in the B

2019-04-02 15:44发布

I'm new to Backbone.

Is it possible to define a Model in backbone which contains a list of Models of the same type? Example:

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
  }
});

I would then have a View which started a recursive call to render(). Example:

MyView = Backbone.View.extend({
  render:function() {
     this.model.render();
  }
});

4条回答
Explosion°爆炸
2楼-- · 2019-04-02 15:55

What you want is a collection. It is basically a list or array of models.

查看更多
做自己的国王
3楼-- · 2019-04-02 16:03

1 no arrays but Collections

Always that you think in an Array of Models in Backbone think in a Collection.

Now what you have to do is implement a Collection of MyModels and keep one instance of it in your MyModel instance.

// 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
});

2 use Views for render

Always that you think in render think in a View.

And the recommend way is that if you have a Collection and a Model better having a View for each one. This way the View of the Collection will call the View of the Model in an iteration:

// 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;
  }
});
查看更多
再贱就再见
4楼-- · 2019-04-02 16:05

Is it possible to define a Model in backbone which contains a list of Models of the same type?

Sure, why not.

var MyModel = Nested.Model.extend();

MyModel.define({
  defaults : {
    nestedMyModels : MyModel.Collection
  },

  addMyModel: function( model ) {
      this.nestedMyModels.add( model );
  }
});

Just not in vanilla Backbone. You'll need a plugin for that. https://github.com/Volicon/backbone.nestedTypes

PS: And as it was mentioned in other responses, you need to use View for rendering stuff. Not models.

查看更多
SAY GOODBYE
5楼-- · 2019-04-02 16:13

Collections are ordered sets of models. For more information check out. http://backbonejs.org/#Collection

Here is an example:

var Library = Backbone.Collection.extend({
  model: Book
});
查看更多
登录 后发表回答