设置骨干模型
我在主干视图中有以下场景。我希望像这样设置模型。
saveField : function(field, val){
//field = 'username'; val = 'Boris'
model.set({field : val});
}
该字段是模型中属性的字符串表示形式。
问题是主干正在通过字段名称创建一个新属性。 我可以这样设置
model.attributes[field] = val;
但是,我宁愿使用 set.
有人知道我该怎么做吗? 谢谢
编辑:最终做了-
var asObj = new Object;
asObj[field] = val;
model.set(asObj);
I have the following scenario in a backbone view. I wish to set the model like so.
saveField : function(field, val){
//field = 'username'; val = 'Boris'
model.set({field : val});
}
The field is a string representation of an attribute in the model.
The problem is that backbone is creating a new attribute by the name of field.
I can set it like so
model.attributes[field] = val;
However, I'd rather use set.
Anyone know how I could do this?
thanks
edit: Ended up doing -
var asObj = new Object;
asObj[field] = val;
model.set(asObj);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看主干源这应该已经可以工作< /strong> - 您的调用只需看起来有点不同即可。
您要查找的参数格式为
set(key, value, options)
。这意味着您一次只能设置一个属性,但看起来这就是您想要做的。另一种格式是set(attr, options)
,这是您正在使用的格式,但不适用于字符串键。无论如何,您不想直接设置该属性,因为主干在内部使用此挂钩来执行诸如引发“已更改”事件之类的操作。
Looking at the backbone source this should already work - your call just needs to look a little different.
The argument format you're looking for is
set(key, value, options)
. This means you can only set one attribute at a time, but it looks like that's all you want to do. The alternative format isset(attr, options)
, which is what you were using but doesn't work with string keys.Regardless, you don't want to set the attribute directly as backbone uses this hook internally to do things like raise the 'changed' event.