我有一个评论集合和一个用于创建新评论的视图。每条评论都会进行一些客户端验证:
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