根据有关验证的主干文档,它指出:
如果 validate 返回错误,set 和 save 将不会继续,模型属性也不会被修改。
因此,如果验证失败,我读取该设置或保存的方式不应该运行。但这不是我得到的结果。即使验证失败,它仍然会发送 POST/PUT 请求。我是在阅读文档错误还是在代码中做错了什么?
这是我的相关代码: https ://gist.github.com/80f6ef0099fbe96025dc
App.Models.Test = Backbone.Model.extend(
urlRoot: '/api/test'
validate: (attrs) ->
errors = []
if attrs.to is ''
errors.push
name: "to"
field: "js-to"
message: "You must enter a to address"
if attrs.subject is ''
errors.push
name: "subject"
field: "js-subject"
message: "You must enter a subject"
# Return our errors array if it isn't empty
errors if errors.length > 0
)
App.Views.Details = Backbone.View.extend(
initialize: ->
@model.bind "error", @error, this
events:
"click #js-save": "saveItem"
saveItem: (e) ->
e.preventDefault()
# Set the model then save it.
@model.set
subject: $("#js-subject").val()
message: $("#js-message").val()
mailbox_id: $("#js-from").val()
to: $("#js-to").val()
cc: $("#js-cc").val()
bcc: $("#js-bcc").val()
tags: App.Helpers.tagsToObject $('#js-tags').val()
scope: $('#js-scope').val()
attachments: attachments
@model.save null,
success: (model, response) =>
App.Helpers.showAlert "Success!", "Saved Successfully", "alert-success"
@next()
error: (model, response) ->
App.Helpers.showAlert "Error", "An error occurred while trying to save this item", "alert-error"
# Show the errors based on validation failure.
error: (model, error) ->
App.Helpers.displayValidationErrors error