我有一组评论和一个用于创建新评论的视图。每条评论都有一些客户端验证:
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
答案 0 :(得分:3)
问题是聚合所有模型事件的集合事件还没有被连接起来。该连接发生在_add()
函数中。由于在添加模型之前验证失败,因此您无法获得该事件。
create
返回false时发生失败的唯一迹象,但看起来你已经知道了这一点。
如果您需要验证错误,则需要找到一种方法来解决错误。
一种方法是在验证器内触发EventAggregator消息。另一种方法是规避或重新定义Collection.create
函数以将错误事件挂钩到模型上。
这样的东西?
model = new Designer.Models.Comment()
model.bind "error", @handleError
if model.set body: $newComment.val()
model.save success: -> @collection.add(model)