我有一个名为Entry
的视图。
class Movieseat.Views.Entry extends Backbone.View
template: JST['movieseats/entry']
className: 'movie-frame'
initialize: ->
@collection.on('change', @render, this)
@collection.on('remove', @render, this)
render: ->
$(@el).html(@template(entry: @collection))
this
events: ->
"click .remove": "removeEntry"
removeEntry: (e) ->
console.log @collection
此视图会创建Entries
模板。
<div data-id="<%= @entry.get('id') %>">
<p><%= @entry.get('title') %></p>
<p><%= @entry.get('id') %></p>
<p class="remove">Remove</p>
</div>
我想要做的是从集合中删除模型(movieseats),然后重新渲染模板。如果我点击一个条目,我会发起console.log @collection
事件。这记录以下内容,
Backbone.Model {cid: "c4", attributes: Object, collection: Movieseats, _changing: false, _previousAttributes: Object…}
我如何定位模型的cid,然后将其从集合中删除?
更新
如果我使用此代码,
removeEntry: (e) ->
thisid = $(e.currentTarget).closest('div').data('id')
console.log @collection
modelToRemove = @collection.findWhere({cid: thisid });
@collection.remove(modelToRemove);
我在控制台日志中得到以下结果。
Backbone.Model {cid: "c4", attributes: Object, collection: Movieseats, _changing: false, _previousAttributes: Object…}_changing: false_events: Object_pending: false_previousAttributes: Objectattributes: Objectchanged: Objectcid: "c4"collection: Movieseatsid: 531__proto__: Object
Uncaught TypeError: undefined is not a function
问题似乎是这部分,
modelToRemove = this.collection
答案 0 :(得分:1)
您可以使用此代码执行此操作(请参阅collection#remove方法):
var modelToRemove = collection.findWhere({cid: "SOME_ID_HERE"});
collection.remove(modelToRemove);
另请参阅findwhere
文档。
从console.log
方法的输出看来,上面代码中的@collection
变量不是真正的Backbone.Collection,而是指向集合的模型。因此,您应该将上面的代码修改为:
trueCollection = @collection.get("collection") // or @collection.collection
modelToRemove = trueCollection.findWhere( cid: "SOME_ID_HERE" )
trueCollection.remove(modelToRemove)