我正在尝试制作一个具有 Post 模型、PostList 集合和 PostView + PostListView 的快速示例 Backbone.js 应用程序。您可以在表单中发布一些简单的东西,它将您的帖子添加到帖子列表中。
当有人在 post 表单上单击提交时,它会在 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