JavaScript [Backbone] new collection 问题

hz_qiuyuanxin · 2013年09月25日 · 最后由 ichord 回复于 2013年09月25日 · 2545 次阅读
class App.Comments extends Backbone.Collection
  model: App.Models.Comment

  parse: (resp, options) ->
    @_counter = resp.data.total_count
    resp.data.comments

在这个 collection fetch 之后,进入这个 parse。

如果 resp.data.comments 为空数组的话,那么 collection.models 里面竟然有一个 comment,但是没啥数据,导致 render view 的时候,render 出了一个空的 view。

截图

截图

看了文档,尝试过返回 []falsenull 都没用,google 了一把,也没找到相关的。

请问有没有人也遇到过这个问题?或是有解决方案的?

应该是你初始化的时候就有一个 comment 吧

#1 楼 @virgil 木有

仅仅如此使用而已

comments = new App.Collections.Comments

然后现在用了一个办法绕过去了,不过始终觉得不好,没有找到其根本所在。

就是监听 collection 的 add 事件,然后在事件里,判断 comment.id?,大致是:

addComment: (comment, collection, options) ->
  if !comment.id? then return

  # Generate view and render it
  commentView = new App.Views.CommentView({model: comment}).render()

  $comments = @$(".comment-list")

 # ......

#2 楼 @hz_qiuyuanxin 看看 qiu.models[0].attributes 里面到底塞了什么?用到了 parse: false 之类的参数么,在 parse 函数里面设置断点或者 console.log 一下?

@hz_qiuyuanxin 设个断点,查看调用链。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号