javascript backbone.js 设置模型属性内部字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8635111/
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
backbone.js set model attribute inner field
提问by Harry
I want to set an attribute of a backbone.js model, but only an inner field rather than the entire field.
我想设置一个backbone.js 模型的属性,但只设置一个内部字段而不是整个字段。
Example code might be:
示例代码可能是:
model.set('user.avatar', 'img')
Anything I can do?
我有什么可以做的吗?
Thanks
谢谢
回答by minikomi
You could simply make a copy of the object, set the attribute, and then re-set it on the original model:
您可以简单地复制对象,设置属性,然后在原始模型上重新设置它:
var userAttributes = model.get("user");
userAttributes.avatar = "img";
model.set("user", userAttributes)
Or add a function to set parts of the user on the model from an object:
或者添加一个函数来从一个对象在模型上设置用户的部分:
model = Backbone.Model.extend({
...
setUser: function(attributes){
var user = this.get("user") || {};
_.extend(user, attributes);
this.set({user:user});
},
...
Then pass in attributes like so: model.setUser({avatar: "img"});
然后像这样传入属性: model.setUser({avatar: "img"});