4

我有一个评论集合和一个用于创建新评论的视图。每条评论都会进行一些客户端验证:

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
4

1 回答 1

3

问题是聚合所有模型事件的集合事件还没有被连接起来。该连接发生在_add()函数中。由于在添加模型之前验证失败,因此您不会收到该事件。

返回 false时会出现唯一的失败迹象,create但看起来您已经发现了这一点。

如果您需要验证错误,则需要想出一种方法来将错误发送给您。

一种方法是在验证器中触发 EventAggregator 消息。另一种是规避或重新定义将Collection.create错误事件挂接到模型上的函数。

像这样的东西?

model = new Designer.Models.Comment()
model.bind "error", @handleError
if model.set body: $newComment.val()
    model.save success: -> @collection.add(model)
于 2011-12-20T11:08:59.510 回答