绑定到由collection.create()创建的模型的错误事件

Bind to error event of a model created by collection.create()?

本文关键字:创建 模型 错误 事件 collection create 绑定      更新时间:2023-09-26

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

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

Comments集合非常简单:

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

问题是聚合所有模型事件的集合事件还没有连接起来。这种连接发生在_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)