Post モデル、PostList コレクション、および PostView + PostListView を持つ簡単なサンプル Backbone.js アプリを作成しようとしています。フォームに投稿できるシンプルなもので、投稿が投稿のリストに追加されます。
誰かが投稿フォームで送信をクリックすると、PostList コレクションのビューである「PostListView」でイベントがトリガーされます。新しい投稿モデルをどこで作成してコレクションに追加しますか? ビュー自体にこのコードを記述しますか? それとも、ビューはこれを行うコレクション メソッドを呼び出しますか? カスタム コレクション メソッドを作成することもできますか? もしそうなら、どうすればそれらをビューから呼び出すことができますか?
Rails のバックグラウンドを持っているので、ビュー (Rails コントローラー) ではなくコレクション/モデルにコードを配置する傾向がありますが、ビューからカスタム コレクション イベントを呼び出す方法がわかりません。
コードは以下の通りです。助けてくれてありがとう!
PostListView.coffee:
class forum.PostListView extends Backbone.View
tagName: 'section'
className: 'post-list'
events:
'click .post-form button': 'submit'
initialize: ->
#causes the view to render whenever the collection's data is loaded
@collection.bind 'reset', @render
@collection.bind 'add', @render
render: =>
$(@el).html JST['postList']()
$postList = this.$('.post-list')
#iterates through posts, renders, appends to <ul>
@collection.each (post) =>
view = new forum.PostView
model: post
collection: @collection
$postList.append view.render().el
return this
submit: ->
console.log "submitted!"
@collection.trigger 'newPost', this.$('.post-form textarea').val()
PostList.coffee:
class forum.PostList extends Backbone.Collection
model: forum.Post
url: '/posts'
initialize: ->
this.bind 'newPost', newPost
newPost: (postText) ->
console.log "Collection method called!!"
# post = new forum.Post
# content: postText
# @add post