There should be a glitch in my syntax, or something I haven’t understood, but when I am doing a save method on my model. The error callback is called whatever the outcome of the method.
@new_activity = new Activity()
@new_activity.save
know: $('input#know').val()
learn: $('input#learn').val()
success: -> console.log 'success'
error: -> console.log 'error'
In my case, since I do not really know whether the new_activity has effectively passed the validation, I have to do an ugly trick to add the activity to the collection. (By the way, I do not use the create method since I do want to have the different errors, and not a simple “false”.
if @new_activity.has('know') and @new_activity.has('learn')
app.collections.activities.add @new_activity
When it is successful though; there is an alert of the created model.
Edit: Further details.
Here is my model:
initialize: ->
_.bindAll @, ‘validate’, ‘errorHandler’
@.bind ‘error’, @errorHandler
validate: (attrs) ->
errors = []
# We only support a certain number of languages, we enforce that the user does not select a wrong set.
if _.isEmpty(_.intersection([attrs.know], ['en', 'fr'])) is true
errors.push 'This language is not currently supported.'
if _.isEmpty(_.intersection([attrs.learn], ['en', 'fr', 'de', 'es', 'zh', 'pt', 'ar', 'ja', 'ru'])) is true
errors.push 'You cannot learn this language yet.'
if _.isEmpty(errors) is false
errors
errorHandler: (model, error) ->
console.log error
When the validation occurs, and if the validate method returns nothing, it still triggers the error event, and the error variable contains the model (but no error message).
You should check whether the new_activity is saved properly, please verify that the server returns success response to the PUT request.
Furthermore, I have had issues with using Rails 3.1 standard
format.json { head :ok }because it returns a single space as a reponse and application/json as content type. Backbone then tries to parse JSON and dies with an error.