0

我正在使用Backbone-nested插件,将我的声明ModelsBackbone.NestedModel.extend()https ://github.com/afeld/backbone-nested

这使我可以这样检索数据:this.model.get('tasks.title')

我遇到的问题是渲染每个嵌套项目。我可以使用 1 输出this.model.get('tasks[0].title')

但是,如果我编写一个循环来迭代每个嵌套的,当在方法return this;之后调用时,将 追加回,它会失败。render()$elCollection $el

问题

如何编写一种有效的方法将嵌套元素呈现到集合视图?

集合视图

App.Views.Tasks = Backbone.View.extend({

        el: '#taskList',

        initialize: function() {
            Event.on('tasks:show', this.show, this);
            this.collection.on('add', this.addOne, this);
        },

        render: function() {
            this.collection.each(this.addOne, this);
            return this;
        },

        addOne: function(project) {
            console.log(project.toJSON());
            var taskView = new App.Views.Task({ model: project });
            this.$el.append(taskView.render().el);
        },

        show: function(id) {
            var project = this.collection.get(id);
            var taskView = new App.Views.Task({ model: project });
            this.$el.html(taskView.render().el);
        }

    });

数据(一个项目)

[
  {
    "_id": "51497f8dc5c3e3ec28ce4571",
    "name": "First Project",
    "tasks": [
      {
        "title": "Second",
        "content": "Lots of content...",
        "deadline": "1-1-2011",
        "status": "in-progress",
        "_id": "51497f8d726694b230000002"
      },
      {
        "title": "Third",
        "content": "Lots of content...",
        "deadline": "1-1-2011",
        "status": "in-progress",
        "_id": "51497fa18aeb50c630000002"
      }
    ]
  }
]
4

1 回答 1

0

关于显示嵌套布局,我似乎多次遇到过这个问题。

有一个位于 Backbone.js 之上的 JavaScript 库,可以减少您必须编写的样板代码量,并且它们有一个 CompositeView 最适合嵌套集合。我已经包含了文档和一篇讨论使用它的文章。

Marionette Composite 查看文档

木偶复合材料 查看文章

我之前回答的一个类似问题

希望这可以帮助。

于 2013-03-20T11:23:38.190 回答