仅使用 Backbone.js 更新某些模型属性
使用 Backbone,我尝试仅更新一个属性并将其保存到服务器:
currentUser.save({hide_explorer_tutorial: 'true'});
但我不想发送所有其他属性。其中一些实际上是服务器端方法的输出,因此它们实际上并不是具有 setter 函数的真正属性。
目前,我正在使用 unset(attribute_name) 删除我不想在服务器上更新的所有属性。问题是这些属性将不再可供本地使用。
关于如何仅将某些属性保存到服务器的建议?
With Backbone, I'm trying to update and save to the server just one attribute:
currentUser.save({hide_explorer_tutorial: 'true'});
but I don't want to send all the other attributes. Some of them are actually the output of methods on the server-side and so they are not actually true attributes with setter functions.
Currently I'm using unset(attribute_name) to remove all the attributes that I don't want to update on the server. Problem is those attributes are then no longer available for local use.
Suggestions on how to only save certain attributes to the server?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
从 Backbone 0.9.9 开始
只需将
{patch:true}
传递给save
函数,如下所示: 文档,
As of Backbone 0.9.9
Just pass
{patch:true}
to thesave
function, like this:From the documentation,
您可以在模型上使用 toJSON 来执行此操作。
这将是保存时发送到后端的唯一属性。
You can use toJSON on the model to do so.
This will be the only attribute sent to the backend on save.
事实上,有一种更简单的方法可以实现这一点,
如果您查看backbone.js第1145行,您会看到这
意味着您可以通过将数据放入选项中来覆盖xhr的数据部分,
因为backbone保存需要model.save( [属性],[选项])
但请记住,像 id 这样的属性可能对于正确保存
示例
对于您的特定情况
这对我来说效果很好,并且可以与 xhr 的任何主干一起使用,例如获取,保存,删除, ...
感谢您的投票
In fact there is a much simpler way of achieving this
if you look at backbone.js line 1145 you will see that
Which means that you may override the data part of the xhr by putting data in your options
Since backbone save requires model.save([attributes], [options])
But remember that attributes like id might be essential to proper saving
Example
For your particular case
This do the trick quite well for me and could be used with any backbone with xhr such as fetch, save, delete, ...
Thanks for voting
我想这目前不可能:Backbone.js 部分模型更新
I guess this isn't currently possible: Backbone.js partial model update
有一个技巧,如果您没有在
options
参数上设置data
属性,而是设置attrs
属性,则请求负载将是attrs
属性值而不是所有模型属性。注意:这也适用于模型创建操作 (POST)。
对于您的特定情况:
您可以从backbone.js 1.33 找到更多详细信息源代码(第1405 - 1409行):
There is a trick, if you do not set
data
property butattrs
property on theoptions
argument, the request payload would be theattrs
property value instead of all the model attributes.Note: This also works for model create actions (POST).
For your particular case:
You can find more details from the backbone.js 1.33 source code (line 1405 - 1409):