【问题标题】:Template doesn't rerender after change in Backbone collection在 Backbone 集合中更改后模板不会重新呈现
【发布时间】:2014-10-26 18:10:55
【问题描述】:

我有一个呈现模板entry 的视图。当模型被添加到集合movieSeats 时,它会执行@collection.on('add', @appendEntry, this) 部分,将模板entry 添加到#entries 容器中。

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)

在不同的视图中,我有一个从集合中删除模型的事件。

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()

这也有效,电影从集合中删除但问题是当我从集合中删除模型时,Entry 视图中的 @collection.on('destroy', @render, this) 不会做任何事情.我必须刷新页面才能看到删除事件的结果。

更新

在这两个视图中,我都将console.log (@collection) 添加到了 div 元素的点击事件中。当我点击一个 div 我得到这个结果,

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

第一个结果来自Entry 视图,第二个结果来自Movieseat 视图。

【问题讨论】:

标签: javascript backbone.js


【解决方案1】:

您是否尝试过在您的收藏中收听remove 事件而不是destroyhttp://backbonejs.org/#Events-catalog

在您的渲染中添加一个快速的 console.log,以检查哪些事件导致视图重新运行该功能。根据我的经验,我总是在集合上使用resetaddremovesort 事件,在个别模型上使用changedestroy 等等。这对我来说更有意义——如果你愿意的话,在语义上。集合不会被破坏,但项目会被删除。 :)

【讨论】:

  • 我已将destroy 替换为remove,但效果并不大。我想我可能已经找到了问题所在。我已经更新了问题。
猜你喜欢
  • 2013-08-30
  • 2021-01-12
  • 2019-01-09
  • 2021-01-26
  • 1970-01-01
  • 1970-01-01
  • 2015-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多