【问题标题】:Return a collection inside a select tag在选择标签内返回一个集合
【发布时间】:2016-10-16 16:33:40
【问题描述】:

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

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

【问题讨论】:

标签: javascript jquery backbone.js


【解决方案1】:

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

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

并在您的模板中使用下划线 _.each 函数像这样将集合潜水到个别面试官

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

它现在必须工作:)

【讨论】:

  • 这只能意味着您没有收到来自您的 json(假服务器)的任何响应
  • 我的服务器收到了响应,一切正常,但视图中没有显示任何内容。
【解决方案2】:

所以,问题与这个问题相同——由于 .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;
    }
});

【讨论】:

    猜你喜欢
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多