Bind to event an error of model created by collection.create () method?

I have a collection of comments and a view that is used to create new comments. Each comment has some client-side validation:

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 

The collection of comments is very simple:

 class Designer.Collections.Comments extends Backbone.Collection model: Designer.Models.Comment 

I am creating comments in the NewComment . This view has access to a collection of comments and uses it to create new comments. However, validation errors in the Comment model do not seem to bubble through the collection. Is there any way to do this?

 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
source share
1 answer

The problem is that the collection event that aggregates all the model events is not yet connected. This connection occurs in _add() . Since validation is not performed before the model is added, you will not receive the event.

The only sign of failure occurs when create returns false, but it looks like you already figured it out.

If you need validation errors, you will need to find a way to get errors from you.

One way would be to disable the EventAggregator message inside the validator. Another would be to bypass or override the Collection.create function to associate the error event with the model.

Something like that?

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

Source: https://habr.com/ru/post/1387165/


All Articles