我有一个呈现模板条目
的 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
事件而不是 destroy
?
http://backbonejs.org/#Events-catalog
将快速 console.log 添加到渲染中,以检查哪些事件导致 View 重新运行该函数。根据我的经验,我总是在集合上使用 reset
、add
、remove
和 sort
事件,并且 对各个模型进行更改
、销毁
等。这对我来说更有意义——从语义上来说,如果你愿意的话。收藏品不会被销毁,但元素会被移除。 :)
关于javascript - 在 Backbone 集合中更改后,模板不会重新呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26571733/