2011-12-20 36 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) 
相关问题