Backbone JS for Restful API上的用户界面

时间:2017-06-27 21:38:58

标签: backbone.js

我正在使用Backbone JS编写UI。后端公开了主干JS在其MVC方法中使用的REST API。到目前为止,在渲染REST资源方面,一切都按预期工作。即我为/as/bs定义了模型和视图,我使用路由在两者之间切换。

现在我想添加一个用于添加/bs的表单,以便我可以发布新的b个实例。表单的一部分是组合框,用户从可能的/as选项中进行选择。我开始将表单附加到用于呈现列表/bs的模板代码。但是对于表单,我也需要获得/as这应该如何运作?

假设我有一个/bs渲染模板,它会迭代每个项目b。表格应该在表格之后,并获取有关/as

的信息
                 <% _.each(items, function(item) { %>
                <tr>
                    <td>
                        <%= item.name %>
                    </td>
                    <td>
                        <%= item.description %>
                    </td>
                <% }); %>

执行此操作的一种方法是将GET /bs的响应扩展为包含所有/as,但不会感到安宁。

另一种选择是让BListView获取这些值并将其作为模板的另一个选项提供。

这里的做法是什么?

1 个答案:

答案 0 :(得分:0)

您可以在视图中包含多个集合。当然,如果您在创建视图时使用collection: myCollection,则myCollection将成为&#34; main&#34;收集,但那就是它。您可以继续使用initialize()方法添加任何您想要的额外收藏

initialize: function() {
  this.anotherCollection = new Backbone.Collection(...);
  // then listen for any event, let's say 'update'
  this.listenTo(this.anotherCollection, 'update', function() {
    //do something in your view, usually, call this.render()
  });
  this.anotherCollection.fetch();
}

然而,此anotherCollection无法在您的模板中自动传递。您必须手动传递它。

template: _.template(theTemplate, {otherCollection: this.anotherCollection})