Backbone: A list of views inside a view

后端 未结 1 1285
忘了有多久
忘了有多久 2021-01-07 00:15

Let me show what I need first so you can understand my problem. I have a contact view like:

ContactView = Backbone.View.extend({
    template: _.template(\"N         


        
相关标签:
1条回答
  • 2021-01-07 00:56

    It looks like you are using underscore.js to render your templates, underscore.js provides a way for rendering a collection within a template (look at the second example). for example

    template: _.template("Name: <%= name %>
                              E-mail: <%= email %>
                              Phones
                    <% _.each(phones, function (phone) { %>
                     <%= label %> - <%= number %>
                    <% }); %>"),
    

    You can also render an individual view for each model and in the same render model modify the el to render it there, but unless you need the view (for example the content will change or you're listening to events) it probably doesn't pay to do it that way. Here's an example of how you could accomplish that

    render: function () {
      this.$el.html(this.model.toJSON());
      _.each(this.model.get('phones'), function(phone) {
        this.$el.find('.phoneArea').append(new phoneView({model: phone}).render().el));
      },this);
      return this;
    }
    

    Also if you were to go this route then note that it would probably pay to cache the views, but again if all you need is to render the content then it would probably pay to just keep the phone numbers as an array and render it within the template.

    0 讨论(0)
提交回复
热议问题