【发布时间】:2013-08-26 22:09:48
【问题描述】:
我已经设置了我的模型验证,如下所示
- 完整的 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()
现在双击进入编辑模式,注意错误是否存在意味着验证已正确完成
【问题讨论】:
-
抱歉,您有什么问题吗?
isValid总是返回true?或者save似乎不起作用? -
@user1248256,问题似乎是
handleError被触发,但在saveTodo,@model.isValid返回true,我在想,这可能是由于模型检测为无效因此没有保存.那么当它转到isValid时,它的有效因为模型没有改变? -
可能
handleError是由save方法触发的?嗯,你在哪里调用save方法? -
在这个版本中,我错过了保存方法。但我认为即使缺少了,这应该仍然有效吗?我希望
isValid返回 false? -
> "尝试添加待办事项,然后尝试将待办事项设为空白。注意它会关闭编辑模式"。看来它对我来说是正确的。当我尝试添加空白待办事项时,我看到“请指定待办事项”,编辑模式未关闭且未添加待办事项。
标签: validation backbone.js coffeescript