2

我有一个与父子关系的模型,我想在表格中显示每个父项,然后是子项,我会稍微缩进子项。我快到了,但我似乎只能将子项附加到父行,而不是在父行之后添加它们。

View.TreeView = Backbone.Marionette.CompositeView.extend({
  template: listItemTpl,
  tagName: "tr",
  initialize: function() {
    var children = new Backbone.Collection(this.model.get('children'));
    if (this.model.get('parent')) {
      this.$el.addClass('child');
    } else {
      this.$el.addClass('parent');
    }
    this.collection = children;
  },

  attachHtml: function(collectionView, childView, index) {
    collectionView.$el.append(childView.el);
  }
});

View.TreeRoot = Backbone.Marionette.CompositeView.extend({
  tagName: "table",
  className: "table table-bordered table-striped",
  childView: View.TreeView,
  template: listTpl,
  childViewContainer: "tbody"
});

我试过了

collectionView.$el.after(childView.el);

但这根本行不通。

我的模型父子是使用如下 Sailsjs 创建的服务器端。

module.exports = {
  schema: true,
  attributes: {
    name: 'string',
    category: {
      model: 'Category'
    },
    parent: {
      model: 'Term'
    },
    children: {
      collection: 'Term',
      via: 'parent'
    }
  }
};
4

1 回答 1

0

我遇到了类似的问题,最终我改用了多个表。将父对象放在 thead 中,将子对象放在 tbody 中。

所以如果你想这样的话,一个提示:

使用compositeView,它的模型是父对象,集合是子对象,它的模板是你的表。在 thead 部分显示您的模型数据,将 childViewContainer 设置为 tbody 并使用 tr 作为 tagName。

(感谢JSteunou @ GitHub)

List.Child = App.Views.ItemView.extend({
  template: "urltotemplate",
  tagName: 'tr'
});

List.Parent = App.Views.CompositeView.extend({
  template: "urltotemplate",
  tagName: 'table',
  childView: List.Child,
  childViewContainer: 'tbody',

  initialize: function(options){
    this.collection = this.model.get("children");
  }
});

List.Parents = App.Views.CompositeView.extend({
  template: "urltotemplate",
  childView: List.Parent,
  childViewContainer: 'div.container'

});
于 2015-04-15T16:06:46.197 回答