javascript 从 Backbone.js 模型中完全删除属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13104548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Completely remove attribute from Backbone.js model
提问by FrizbeeFanatic14
I am trying to totally remove an attribute from a backbone model. The model is being sent to an API that isn't very flexible, and it will break if I send additional attributes over the ones I'm supposed to send, so I need to remove an attribute so it no longer exists.
我试图从主干模型中完全删除一个属性。模型被发送到一个不是很灵活的 API,如果我发送额外的属性而不是我应该发送的属性,它会中断,所以我需要删除一个属性,使其不再存在。
I tried model.unset
, from this question, but when I print out the object the attribute I'm trying to remove is still listed, just with a value of null.
我试过model.unset
,从这个问题,但是当我打印出对象时,我试图删除的属性仍然列出,只是值为空。
I need the attribute to be completely gone.
我需要属性完全消失。
My basic structure is:
我的基本结构是:
model.unset("AttrName", "silent");
回答by McGarnagle
The problem is that you're using the parameters for unset
incorrectly. "Silent" should be a part of an options hash, not a separate parameter. This works:
问题是您使用的参数unset
不正确。"Silent" 应该是options hash的一部分,而不是单独的参数。这有效:
model.unset("AttrName", { silent: true });
The reason for the strange behavior can be seen from the annotated source:
从注释的来源可以看出奇怪行为的原因:
unset: function(attr, options) {
(options || (options = {})).unset = true;
return this.set(attr, null, options);
},
The unset
method assumes that its options
parameter is an object, and attempts to either create or modify it, then passes it on to the set
method. If you pass a string instead, then the inadvertent effect of the code is to set the attribute to null, rather than to unset it.
该unset
方法假定其options
参数是一个对象,并尝试创建或修改它,然后将其传递给该set
方法。如果改为传递字符串,则代码的无意影响是将该属性设置为 null,而不是取消设置它。
回答by Tal Bereznitskey
Override the toJSON method of your model and only include the attributes you wish to send.
覆盖模型的 toJSON 方法,只包含您希望发送的属性。
Updated: (added code sample)
更新:(添加代码示例)
When extending the model, add a toJSON function and return an object with the desired attributes:
在扩展模型时,添加一个 toJSON 函数并返回一个具有所需属性的对象:
{
toJSON : function() {
return {
name: this.get('name'),
age: this.get('age'),
phoneNumber: this.get('phoneNumber')
};
}
}
回答by poorman
You might try just building an object with only the properties you want (and sending that):
您可以尝试仅使用您想要的属性构建一个对象(并发送它):
serializeModel: function() {
return {
email: this.$("#email").val(),
password: this.$("#password").val()
}
}