如何使用Undercore和Backbone在HTML中表示模型属性

How to represent model attributes wtihin HTML using Underscore and Backbone

本文关键字:表示 模型 属性 HTML 何使用 Undercore Backbone      更新时间:2023-09-26

我有一个应用程序,它显示框中框。每个框模型都有一个方法"children",该方法返回框中显示的任何框。我想做的是单击一个按钮,将子项呈现为一个表,其属性列在几列中。

我真的不知道该怎么做。我认为Undercore模板可能看起来像这样:

<table class='list-items-template'>
          <tr>
          <td><%= this.model.ITSCHILDX.get('image') %>       </td>
          <td><%= this.model.ITSCHILDX.get('title') %>       </td>
          <td><%= this.model.ITSCHILDX.get('description') %> </td>
          </tr>
      </table>

但是,在Box视图中,我需要用某种方式来表示每个子项都应该插入到表中,并且应该表示它的每个属性。非常感谢您的帮助。

您可以通过在模板中插入代码块来将迭代逻辑添加到模板中。修改您的示例:

<table class='list-items-template'>
    <% for (var idx in this.model.ITSCHILDX) { %>
        <tr>
            <td><%= this.model.ITSCHILDX[idx].get('image') %></td>    
            <td><%= this.model.ITSCHILDX[idx].get('title') %></td>    
            <td><%= this.model.ITSCHILDX[idx].get('description') %></td>    
        </tr>
    <% } %>
</table>

不确定我是否正确理解设置,但您有一个BoxModel。

BoxModel = Backbone.Model.extend({
    defaults: {
        'image':string,
        'title':string,
        'description':string
    }
});

BoxModel可以包含子BoxModel吗?

boxModel.children = new Collection(); // of box models?

您想遍历children集合并将每个模型表示为表行吗?

如果这是你想要的,我会这么做。一个盒子模型由一个BoxView表示,它是一个表,它的子级基本上用行表示。因此,我们将其定义为:

BoxView = Backbone.View.extend({
    tagName: 'table',
    className: 'list-items-template', // I just used this name to connect it with your ex.
                                      // I'd probably change it to like, box-table
    template: _.template('<tr>
        <td><%= image %>       </td>
        <td><%= title %>       </td>
        <td><%= description %> </td>
        </tr>'),
    initialize: function() {
        // Note: We've passed in a box model and a box model has a property called
        // children that is a collection of other box models
        this.box = this.model;
        this.collection = this.box.children // Important! Assumes collection exists.
    },
    render: function() {
        this.$el.html(this.addAllRows());
        return this;
    },
    addAllRows: function() {
        var that = this;
        var rows = '';
        this.collection.each(function(box) {
            rows += that.template(box.toJSON());
        });
        return rows;
    }
});

// This assumes that whatever BoxModel you have instantiated, it has a property called
// children that is a collection of other BoxModels. We pass this in.
// Get the party started
var myBoxTable = new BoxView({
    'model': someBoxModel  // Your box model, it has a collection of children boxModels
});
// Throw it into your page wherever.
$('#placeToInsert').html(myBoxTable.render.el());

还要注意,这基本上意味着您的子boxModel在本例中以视觉方式表示。如果每个子(行)都必须具有一些功能,而不是仅仅使用模板来编写可视化表示,我会使用addAllRows()方法来实例化第二种类型的BoxModel视图。一个视图,它是一个表行,具有更多的功能,如正确委派的事件。