我想做一个快速示例Backbone.js应用程序,它有Post模型,PostList集合和PostView + PostListView。一些简单的地方,你可以在表单中发帖,它会将你的帖子添加到帖子列表中。Backbone.js - 代码来创建一个新的职位去哪里去?
当有人点击提交表单后,它会在“PostListView”中触发一个事件,这是PostList集合的视图。我在哪里创建一个新的后期模型并将其添加到集合?我是否在View中编写这段代码?或者视图调用这样做的收集方法?你甚至可以编写自定义收集方法吗?如果是这样,我如何从视图中调用它们?我自然倾向于将代码放入集合/模型而不是视图(rails controllers),但我无法弄清楚如何从视图调用自定义集合事件。
代码如下。非常感谢您的帮助!
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
感谢所有三个提示!很有用!清理了很多。 在服务器上保存记录后是否触发了一个事件我可以将添加到集合的代码绑定到? – hurshagrawal
默认情况下没有。虽然在我的应用程序中,我总是添加这个。您可以在成功回调中调用add,或者在成功回调中触发一个事件,这会导致其他操作进行添加。 – maxl0rd