javascript - 在 Backbone 集合中更改后,模板不会重新呈现

标签 javascript backbone.js

我有一个呈现模板条目的 View 。当模型添加到集合 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)

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

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

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

更新

在这两个 View 中,我都将 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 View ,第二个结果来自 Movieseat View 。

最佳答案

您是否尝试过监听集合上的 remove 事件而不是 destroyhttp://backbonejs.org/#Events-catalog

将快速 console.log 添加到渲染中,以检查哪些事件导致 View 重新运行该函数。根据我的经验,我总是在集合上使用 resetaddremovesort 事件,并且 对各个模型进行更改销毁等。这对我来说更有意义——从语义上来说,如果你愿意的话。收藏品不会被销毁,但元素会被移除。 :)

关于javascript - 在 Backbone 集合中更改后,模板不会重新呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26571733/

相关文章:

javascript - 为什么我在localStorage中设置的和我得到的不一样?

angularjs - 为什么单页应用程序通常必须在每个页面发出更多请求时速度更快?

javascript - 将参数传递给主干中的事件

javascript - 基于另一个 Backbone 模型初始化 Backbone 模型

javascript - 打开后自动刷新可折叠内容

javascript - 展开/折叠跨度?

javascript - jquery 表单序列化 - 没有传递任何东西...但 console.log 很好

javascript - 单击选择选项后如何更新页面上的内容?

javascript - 如何使从 cordova-plugin-file-transfer 上传的函数返回一个 promise

javascript - Mongoose,将 `.aggregate()` 应用于子文档数组,并以最少的查询次数获得文档其他字段的结果