Return collection 在 select 标签内

Return a collection inside a select tag

我有 collection 个具有不同属性的模型,我需要在 <select> 标签内渲染其中的一些模型,每个模型作为一个 <option>。呈现此 collection 的视图嵌套在另一个视图中。这是我的 collection:

var UserCollection = Backbone.Collection.extend({
    url: 'http://localhost:3000',

    developers: function () {
        var developers = this.where({role: "developer"});
        return new UserCollection(developers);
    }
});

这是我对 select 标签的看法:

var InterviewersView = Backbone.View.extend({
    initialize: function () {
        this.template = _.template(interviewersTemplate);
        this.collection = new UserCollection();
        this.collection.fetch();
        this.interviewers = this.collection.developers();
    },

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

这是我的模板:

<label>Interviewer</label>
<select class="form-control" id="js-interviewer-selector">
    <% _.each(this.interviewers.toJSON(), function(interviewer) { %>
      <option value="<%= interviewer.login %>">
        <%= interviewer.firstName %> <%= interviewer.lastName %>
      </option>
    <% }) %>
</select>

模板在另一个视图中正确呈现,完全按照我的需要呈现,但 select 标记内没有选项,它是空的。我做错了什么?

Repo with my project

尝试像这样将您的 collection 传递给您的视图

render: function () { 
    var that  = this;
    that.$el.html(that.template({interviewers: that.interviewers}));
    return this;
}

并在您的模板中使用下划线 _.each 函数来 collection 像这样

<select class="form-control" id="js-interviewer-selector">
<% _.each(interviewers, function(interviewer) { %>
  <option value="<%= interviewer.login %>">
    <%= interviewer.firstName %> <%= interviewer.lastName %>
  </option>
<% }) %>
</select>

现在一定可以了:)

因此,问题与此问题相同——由于 .fetch() 方法的异步性质,集合是在呈现视图后加载的,因此它什么也没收到。因此,从 initialize 中删除 .fetch() 方法并将其添加到 render 有效。完整代码如下:

var InterviewersSelect = Backbone.View.extend({
    initialize: function () {
        this.template = _.template(interviewersTemplate);
        this.collection = new UserCollection();
    },

    render: function () {
        var self = this;

        this.collection.fetch({
            data: {
                role: "developer"
            },

            success: function(collection) {
                var interviewers = collection.map(function(item) {
                    return item.toJSON();
                });
                self.$el.html(self.template({interviewers: interviewers}));
            }
        });

        return this;
    }
});