포스트 모델, PostList 컬렉션 및 PostView + PostListView가있는 빠른 샘플 Backbone.js 앱을 만들려고합니다. 양식에 간단하게 게시 할 수 있고 게시물 목록에 게시물을 추가하는 간단한 방법입니다.Backbone.js - 새 게시물을 만드는 코드는 어디에 있습니까?
누군가가 게시 양식에서 제출을 클릭하면 PostList 수집을위한보기 인 "PostListView"에서 이벤트를 트리거합니다. 새 게시물 모델을 만들고 컬렉션에 추가하려면 어떻게해야합니까? View 자체에이 코드를 작성합니까? 또는 뷰가 이것을 수행하는 콜렉션 메소드를 호출합니까? 커스텀 콜렉션 메소드를 작성할 수 있습니까? 그렇다면 뷰에서 어떻게 호출 할 수 있습니까?
레일 배경에서 볼 때 뷰 (레일 컨트롤러)보다는 컬렉션/모델에 자연스럽게 코드를 삽입하지만 뷰에서 사용자 지정 컬렉션 이벤트를 호출하는 방법을 알 수 없습니다.
코드는 다음과 같습니다. 어떤 도움을 주셔서 감사합니다!
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 : 당신은 컬렉션에 새로운 모델을 추가하려면 PostListView
에서, PostList
의 메소드를 호출
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