【发布时间】:2012-12-30 09:28:29
【问题描述】:
没有多少谷歌搜索能够解决我的困惑,所以我想我会在这里问这个问题。
我正在尝试保存模型并使用成功/错误回调。在backbone documentation 上,它声明您保存模型,如下所示:model.save([attributes], [options])。
我在文档中找不到任何地方告诉您如何保存整个模型(即不指定属性),但遇到了this question,第二个答案说要保存整个模型,您可以这样做model.save({}, [options]) .
但是我尝试这样做无济于事。我的代码如下:
主干模型:
class Student extends Backbone.Model
url: ->
'/students' + (if @isNew() then '' else '/' + @id)
validation:
first_name:
required: true
last_name:
required: true
email:
required: true
pattern: 'email'
schema: ->
first_name:
type: "Text"
title: "First Name"
last_name:
type: "Text"
title: "Last Name"
email:
type: "Text"
title: "Email"
在我看来,我有以下功能:
class Students extends CPP.Views.Base
...
saveModel = ->
console.log "model before", @model.validate()
console.log "model attrs", @model.attributes
@model.save {},
wait: true
success: (model, response) ->
notify "success", "Updated Profile"
error: (model, response) =>
console.log "model after", @model.validate()
console.log "model after is valid", @model.isValid()
console.log "response", response
notify "error", "Couldn't Update"
在保存之前的第一个 console.log 中,我被告知模型是有效的,通过 undefined 响应。如果我确实查看模型,我可以看到所有三个字段都已填写。
类似地,在接下来的两个控制台日志中,错误@model.validate() 和@model.isValid() 都分别返回undefined 和true。
但是我尝试保存模型得到的响应是Object {first_name: "First name is required", last_name: "Last name is required", email: "Email is required"}
最后在我得到的模型属性的console.log中:
Object
created_at: "2012-12-29 23:14:54"
email: "email@email.com"
first_name: "John"
id: 2
last_name: "Doe"
type: "Student"
updated_at: "2012-12-30 09:25:01"
__proto__: Object
这让我相信,当我将 {} 传递给我的模型时,它实际上是在尝试将属性保存为 nil,否则为什么会出错?
有人可以指出我做错了什么吗?我宁愿不必将每个属性单独传递给保存!
提前致谢
【问题讨论】: