2011-12-20 2 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를 반환 할 때만 오류가 발생하지만 이미 알아 냈습니다.

유효성 검사 오류가 필요한 경우 오류를 얻을 수있는 방법을 찾아야합니다.

한 가지 방법은 유효성 검사기 내부의 EventAggregator 메시지를 실행하는 것입니다. 다른 하나는 모델에 오류 이벤트를 연결하기 위해 Collection.create 함수를 우회하거나 다시 정의하는 것입니다.

이와 비슷한?

model = new Designer.Models.Comment() 
model.bind "error", @handleError 
if model.set body: $newComment.val() 
    model.save success: -> @collection.add(model) 
관련 문제