我已经设置了我的模型验证,如下所示
- 完整的 CoffeeScript 代码: http: //pastebin.com/3isZZke8
- JS Fiddle 演示:http: //jsfiddle.net/XKTnb/
模型验证
class Todo extends Backbone.Model
validate: (attrs) ->
errs = {}
hasErrors = false
if (attrs.title is "")
hasErrors = true
errs.title = "Please specify a todo"
if hasErrors
return errs
View中的错误相关代码
class TodoView extends Backbone.View
events:
"keypress .editing input[name=todo]": "saveTodo"
"keyup .editing input[name=todo]": "closeEdit"
"blur input[name=todo]": "clearErrors"
initialize: ->
...
@model.bind("change", @render)
@model.bind("error", @handleError)
saveTodo: (e) ->
if e.type is "keypress" and e.charCode isnt 13
return
@model.set("title": @$("input[name=todo]").val())
console.log @$("input[name=todo]").val() + "...", @model.isValid(), @model.get("title")
if @model.isValid()
@closeEdit()
closeEdit: (e) ->
if (e)
if e.type is "keyup" and e.keyCode isnt 27 then return
@$el.removeClass("editing")
handleError: (model, errs) ->
@clearErrors()
@$("input[name=todo]").after($("<span />", {
class: "error",
html: errs.title
}));
console.log "error handled"
clearErrors: ->
@$el.remove(".error")
在TodoView.saveTodo
中,我检查模型是否有效,如果是,我希望save
成功并希望退出编辑编辑模式。但是,它似乎isValid
总是true
,也许是因为发生了验证,因此模型没有保存在有效状态?
更新
在上面添加了指向 JS Fiddle 的链接。尝试添加待办事项,然后尝试将待办事项设为空白。请注意,它关闭了编辑模式,尽管在我的代码中:
saveTodo: (e) ->
if e.type is "keypress" and e.charCode isnt 13
return
@model.set("title", @$("input[name=todo]").val())
if @model.isValid() # model appears to be valid here!
@model.save()
@closeEdit()
现在双击进入编辑模式,注意错误是否存在意味着验证已正确完成