再多的谷歌搜索也无法解决我的困惑,所以我想我应该在这里问这个问题。
我正在尝试保存模型并使用成功/错误回调。关于backbone documentation它指出您可以像这样保存模型:model.save([attributes], [options])
。
我在文档中找不到任何地方可以告诉您如何保存整个模型(即不指定属性),但遇到了 this question其中第二个答案表示要保存整个模型,您可以执行 model.save({}, [options])
。
但是我尝试这样做没有成功。我的代码如下:
Backbone 模型:
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 中,我通过 未定义
响应得知该模型是有效的。如果我确实查看模型,我可以看到所有三个字段都已填写。
类似地,在接下来的两个控制台日志中,错误 @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: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93f6fef2faffd3f6fef2faffbdf0fcfe" rel="noreferrer noopener nofollow">[email protected]</a>"
first_name: "John"
id: 2
last_name: "Doe"
type: "Student"
updated_at: "2012-12-30 09:25:01"
__proto__: Object
这让我相信,当我将 {}
传递给模型时,它实际上是在尝试将属性保存为 nil,否则为什么会出错?
有人可以指出我做错了什么吗?我不想将每个属性单独传递到保存!
提前致谢
最佳答案
来自 Hui Zheng
的建议答案我修改了服务器中的 Controller ,以 JSON 格式返回学生。
但是为了找到问题的真正根源,我阅读了 backbone documentation保存时,发现当 wait: true
作为一个选项给出,它执行以下操作:
if (!done && options.wait) {
this.clear(silentOptions);
this.set(current, silentOptions);
}
在进一步调查清楚后我发现
clear: function(options) {
var attrs = {};
for (var key in this.attributes) attrs[key] = void 0;
return this.set(attrs, _.extend({}, options, {unset: true}));
},
从这里看来,好像每个属性都被清除然后被重置。然而,在清除我的模型时,我编写的验证将失败(因为 first_name
、 last_name
、 email
是必需的)。
关于backbone.validation documentation我们被告知可以使用参数 forceUpdate: true
,所以我选择在保存模型时使用它。我现在假设(尽管这可能不是一个好的做法)来自服务器的数据是正确的,因为这也已经过验证。
因此我的最终代码是:
saveModel = ->
@model.save {},
wait: true
forceUpdate: true
success: (model, response) ->
notify "success", "Updated Profile"
error: (model, response) ->
notify "error", "Couldn't Update"
关于backbone.js - 主干模型保存,验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14089679/