【问题标题】:Is it possible to remove a model by cid?是否可以通过 cid 删除模型?
【发布时间】: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


【解决方案1】:

您可以使用此代码(请参阅collection#remove 方法):

var modelToRemove = collection.findWhere({cid: "SOME_ID_HERE"});
collection.remove(modelToRemove);

另请参阅findwhere docs。

编辑

console.log 方法的输出看来,上述代码中的@collection 变量不是真正的Backbone.Collection,而是指向集合的模型。因此,您应该将上面的代码修改为:

trueCollection = @collection.get("collection") // or @collection.collection
modelToRemove = trueCollection.findWhere( cid: "SOME_ID_HERE" )
trueCollection.remove(modelToRemove)

【讨论】:

  • 我已经更新了我的代码,但是得到了一个未捕获的类型错误。你能检查一下这个问题吗?
  • 我认为CoffeeScript中不应该有花括号
  • 错误发生在此之前。它发生在collection.findWhere
  • 这很奇怪。您是否有机会创建一个 js-fiddle 来演示该问题?
  • .findWhere( cid: "SOME_ID_HERE" ) "SOME_ID_HERE" 是什么意思?我是否应该创建一个变量来存储正在单击的模型模型的 CID,然后将其放在上面代码中的 .findWhere( cid: ... )' ? Like the thisid` 中,然后是 cid?
猜你喜欢
  • 2012-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-28
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多