collectionにmodelをcreateしたときに追加したやつが最後にくるのをなんとかしたい件
あるユーザーのなんかの投稿に対して、別のユーザーがコメントできるのはよくあるじゃないですか。
それをbackbone.jsでやろうとするとModelsとCollectionsをそれぞれ実装することになると思う。
こんな感じ
- Models.Comment
class YourAPP.Models.Comment extends Backbone.RelationalModel YourAPP.Models.Comment.setup()
- Collections.Comments
class YourAPP.Collections.Comments extends Backbone.Collection url: () -> postId = this.post.get("id") '/posts/' + postId + '/comments' model: YourAPP.Models.Comment
で、Viewでは、こんな感じにしとけば、コメントの一覧は表示されるでしょう。
で、このコメント一覧は投稿フォームも備えてて、そこにコメント入力するとコメント一覧が更新される、と。
- YourAPP.Views.Comment
class YourAPP.Views.Comment extends Backbone.View el: '#comment-area' template: JST['posts/comment_list'] events: { "click #comment-post-btn" : "post" } initialize: () -> @post = this.options.post @comments = @post.get("comments") @comments.on('reset', @render, this) @comments.on('change', @render, this) @comments.fetch() @$textArea = $(@el).find("#comment-textarea") render: () -> $(@el).children("#comment-list").html(@template(comments: @comments.models)) post: (evt) -> evt.preventDefault() @comments.create content: @$textArea.val()
※Routerで new YourAPP.Views.Comment({post: @post})しておく。
backbone便利だわー。便利っていうか整理されるわー。これで、上記の仕様どおりにほぼうごくんだけど、残念なのが新しいコメントがコメント一覧の最後に追加されちゃう。先頭に追加させたいんです。ほんとは。
調べたけど、create時に新しい要素の先頭に追加する、的なことはムリっぽい。なので追加されるときにソートするようにした。
Collectionにソートするときの方法のひとつとしてcomparatorを実装しておく、というのがある。
- Collections.Comments
class YourAPP.Collections.Comments extends Backbone.Collection url: () -> postId = this.post.get("id") '/posts/' + postId + '/comments' comparator: (model) -> model.get("id") * -1 model: YourAPP.Models.Comment
IDの降順にしておく。
でもってViewのrenderのタイミングでsortをかます。
render: () ->
@comments.sort()
$(@el).children("#comment-list").html(@template(comments: @comments.models))
これで、OK牧場。