Peter Boomsma
Peter Boomsma

Reputation: 9808

Template doesn't rerender after change in Backbone collection

I have a view which renders a template entry. When the a model gets added to the collection movieSeats it does the @collection.on('add', @appendEntry, this) part which adds the template entry to the #entries container.

class Movieseat.Views.Entry extends Backbone.View

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

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

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

  events: ->
    "click div":"showCollection"

  showCollection: ->
    console.log @collection

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

On a different view I have a event that removes a model from the collection.

class Movieseat.Views.MovieseatsIndex extends Backbone.View

  template: JST['movieseats/index']

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

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

  addEntry: (e) -> 
    movie_title = $(e.target).text()
    @collection.create title: movie_title

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

This also works, the movie gets removed from the collection but the problem is that when I remove a model from the collection, the @collection.on('destroy', @render, this) from the Entry view doesn't do anything. I have to refresh the page to see the result of the remove event.

update

In both views I've added console.log (@collection) to a click event on a div element. When I click on a div I get this result,

Backbone.Model {cid: "c5", attributes: Object, collection: Movieseats, _changing: false, _previousAttributes: Object…}
Movieseats {length: 8, models: Array[8], _byId: Object, _events: Object, constructor: function…}` 

The first result is from the Entry view and the seconde from the Movieseat view.

Upvotes: 0

Views: 460

Answers (1)

CharlieBrown
CharlieBrown

Reputation: 4163

Have you tried listening to the remove event on your collection instead of destroy? http://backbonejs.org/#Events-catalog

Add a quick console.log to your render to check which events are causing the view to re-run that function. In my experience, I always use reset, add, remove and sort events on collections, and change, destroy, and so on on individual models. It just makes more sense -semantically if you will- to me. Collections are not destroyed, but items are removed. :)

Upvotes: 1

Related Questions