不确定如何使用 Backbone 和下划线模板来模板化数组对象

Not sure how to template object of arrays using Backbone and Underscore templates

我有一个集合,其中返回的数据如下所示:

{
  "departments": ["Customer Support", "Marketing"],
  "classes": ["Planning", "Drawing"]
}

我不太确定如何使用下划线模板循环来输出每个部门,现在我正在使用 ._each 但我的输出是 object Object。谁能建议如何解决这个问题?

Fiddle: http://jsfiddle.net/kyllle/aatc70Lo/7/

模板

<script type="text/template" class="js-department">
    <select>
        <% _.each(departments, function(department) { %>
            <option value="<% department %>"><% department %></option>
        <% }) %>
    </select>
</script>

JS

var Department = Backbone.Model.extend();

var Departments = Backbone.Collection.extend({
    model: Department,
    parse: function(response) {
        return response;
    }
});

var DepartmentView = Backbone.View.extend({
    template: '.js-department',

    initialize: function() {
        console.log('DepartmentView::initialize', this.collection.toJSON());
    },

    render: function() {
        this.$el.html( this.template( this.collection.toJSON() ) );
    }
});

var departments = new Departments({
  "departments": ["Customer Support", "Marketing"]
}, {parse:true});

var departmentView = new DepartmentView({
    collection: departments
});

document.body.innerHTML = departmentView;
  1. 您甚至没有调用 render(),因此您的模板从未执行过,object Object 输出与您的模板无关。
  2. 你以后运行render()你会发现
    template: '.js-department'
    不起作用,因为它不是 Marionette,并且 Backbone 不会通过选择器为您编译 html。所以你将用这样的东西替换它:
    template: _.template($('.js-department').html())
  3. 然后你必须意识到 this.collection 是一个数组,只有一个项目,所以如果你只想渲染第一个项目,你将把它发送到模板:
    this.$el.html( this.template( this.collection.first().toJSON() ) );
  4. 然后你将不得不意识到 departmentView 是一个 Backbone.View 实例对象,而不是 html 本身。它具有 el 属性,这是此视图实例的 DOM 元素,以及 $el 属性,这是包装的相同 DOM 元素jQuery.
  5. document.body.innerHTML = departmentView.el 仍然不起作用,因为 innerHTML 需要一个字符串。所以你可以改为做类似
    的事情 document.body.appendChild( departmentView.el );
    departmentView.$el.appendTo( document.body ); 与 jquery.
    (要使最后一个工作 render 必须 return this

工作 jsfiddle:http://jsfiddle.net/yuraji/zuv01arh/