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

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
4

1 に答える 1

3

問題は、すべてのモデルイベントを集約するコレクションイベントがまだ接続されていないことです。そのフックアップは_add()関数で発生します。モデルが追加される前に検証が失敗するため、イベントは発生しません。

falseを返す場合に失敗の唯一の兆候が発生しcreateますが、すでにそれを理解しているようです。

検証エラーが必要な場合は、エラーを取得する方法を考え出す必要があります。

1つの方法は、バリデーター内でEventAggregatorメッセージを起動することです。もう1つは、関数を回避または再定義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 に答える