2011-12-20 7 views
4

私は、コメントのコレクションと新しいコメントを作成するために使用されるビューを持っています。各コメントが起こっているいくつかのクライアント側の検証を持っていますcollection.create()によって作成されたモデルのエラーイベントにバインドしますか?

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 

答えて

3

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

createがfalseを返すだけで、障害が発生していることがわかりますが、それがすでにわかっているようです。

検証エラーが必要な場合は、エラーを受け取る方法を提示する必要があります。

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) 
関連する問題