私は、コメントのコレクションと新しいコメントを作成するために使用されるビューを持っています。各コメントが起こっているいくつかのクライアント側の検証を持っていますcollection.create()によって作成されたモデルのエラーイベントにバインドしますか?
class Designer.Models.Comment extends Backbone.Model
validate: (attrs) ->
errors = []
# require presence of the body attribte
if _.isEmpty attrs.body
errors.push {"body":["can't be blank"]}
unless _.isEmpty errors
errors
コメントのコレクションは、超簡単です:
class Designer.Collections.Comments extends Backbone.Collection
model: Designer.Models.Comment
私はNewComment
ビューでコメントを作成します。このビューはコメントコレクションにアクセスし、それをcreate
新しいコメントに使用します。しかし、Comment
モデルで検証が失敗しても、コレクションをバブルアップするようなことはありません。これを行うためのバッター方法はありますか?
class Designer.Views.NewComment extends Backbone.View
events:
'submit .new_comment' : 'handleSubmit'
initialize: ->
# this is where the problem is. I'm trying to bind to error events
# in the model created by the collection
@collection.bind 'error', @handleError
handleSubmit: (e) ->
e.preventDefault()
$newComment = this.$('#comment_body')
# this does fail (doesn't hit the server) if I try to create a comment with a blank 'body'
if @collection.create { body: $newComment.val() }
$newComment.val ''
this
# this never gets called
handleError: (model, errors) =>
console.log "Error registered", args