2016-10-16 17 views
0

我有一个具有不同属性的模型集合,我需要在<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

+0

尝试添加分号;在每个方法的末尾。 – Mahi

+0

http://stackoverflow.com/questions/9154628/rendering-backbone-js-collection-as-a-select-list – Mahi

+0

@mahendrapratapjewaria我已经看过这个问题和答案,但不幸的是,这并没有帮助足够的 – AlexNikolaev94

回答

1

因此,问题与此问题相同 - 由于.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; 
    } 
}); 
1

尝试到您的收藏传递给你的看法是这样

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

,并在模板中使用下划线_.each功能潜水收集个人interviwer这样

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

它现在必须工作:)

+0

不幸的是,没有工作:( – AlexNikolaev94

+0

这只能意味着你没有收到你的json(假服务器)的任何回应 –

+0

我得到了我的服务器的响应,它是好的,但没有什么显示内视图。 – AlexNikolaev94