【发布时间】:2014-10-27 10:28:21
【问题描述】:
我有一个名为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
【问题讨论】:
-
在你看来
@collection真的是一个集合吗?如果它是一个模型,那么请称它为@model以避免所有这些混淆。视图连接@model的方式与连接@collection的方式相同,因此您可以称其为。
标签: backbone.js collections model coffeescript