Render template inside template using Backbone

2019-09-06 17:19发布

问题:

I've got two views. The first view renders the entry template containing data from that collection in a list element.

class Movieseat.Views.Entry extends Backbone.View

  template: JST['movieseats/entry']
  className: 'movie-frame'

  render: -> 
    $(@el).html(@template(entry: @collection))
    this

The second view rerenders the above said template inside a #entries div which is being rendered in this #showentry template.

class Movieseat.Views.Showentry extends Backbone.View

  template: JST['movieseats/showentry']
  className: 'showmovie'

  initialize: -> 
    @collection.on('destroy', @render, this)
    @collection.on('change', @render, this)
    @collection.on('add', @appendEntry, this)
    return

  render: -> 
    $(@el).html(@template(entry: @collection))
    this

  events: -> 
    "click .remove":    "destroyEntry"

  appendEntry: (entry) ->
    view = new Movieseat.Views.Entry(collection: entry)
    $('#entries').append(view.render().el)

  destroyEntry: (e) -> 
    thisid = @$(e.currentTarget).closest('div').data('id')
    @collection.get(thisid).destroy()

This is the template structure,

Entry template,

<div data-id="<%= @entry.get('id') %>">
    <p><%= @entry.get('title') %></p>
    <p><%= @entry.get('id') %></p>
    <p class="remove">Remove</p>
</div>

ShowEntry template

<div id="entries"></div>

When I load the page the models get rendered in the entry template from the first view. Then the second view takes all the entries in the collection and appends them to the #entries div container.

When I do action like delete or change a collection the second view rerenders the showentry template. But when it does that it does not repopulate the #entries with the models from the collection. Resulting in a empty #entries div, where before it was filled with .movie-frame divs containing models.

Is there a way to fix this?