绑定到由collection.create()创建的模型的错误事件
Bind to error event of a model created by 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
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)
相关文章:
- 取消在集合中创建模型.与重复作战
- Mongoosejs:如何在没有Schema的情况下创建模型
- 如何创建模型的实例并加载它
- 煎茶触摸 2 商店 - 在创建模型之前修改响应
- 使用猫鼬重新创建模型
- 使用AngularJS创建模型
- 正在获取已创建模型的ID字段
- 在EmberJS中创建模型实例的问题
- 在单独的文件中使用Sequelize创建模型,并在项目中使用它们
- 当模型依赖于另一个模型时创建模型
- 当模式位于单独的文件中时,创建模型时是否存在任何问题
- 当在环回中创建模型实例时,如何以编程方式填充字段
- 在expressjs中创建模型
- 在Backbone.js中从非json服务器响应创建模型实例
- 如何在动作链接中传递选择列表值,而不使用javascript并为其创建模型
- 在Javascript中创建模型对象列表
- 使用不同的URL来创建模型的主干方法是什么?
- 创建模型可以清除屏幕
- 从带有主干的服务器获取数据,创建模型和集合
- Node.js从json创建模型对象