设置骨干机型 [英] setting backbone models

查看:89
本文介绍了设置骨干机型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个骨干视图以下情形。我要设置的模式,像这样。

  saveField:功能(场,VAL){
    //字段='用户名'; VAL =鲍里斯
model.set({场:VAL});
}

字段是一个字符串,再在模型的属性presentation。

的问题是,主链创建由场的名称的新的属性。
我可以设置它像这样

  model.attributes [现场] = VAL;

不过,我宁愿使用设置。

有谁知道我能做到这一点?
谢谢

编辑:终于实现了 -

  VAR asObj =新对象;
asObj [现场] = VAL;
model.set(asObj);


解决方案

纵观骨干的来源 这应该已经工作 - 您的通话只需要看起来有点不同。

  saveField:功能(场,VAL){
    //字段='用户名'; VAL =鲍里斯
    model.set(场,VAL);
}

您正在寻找的参数格式是设置(键,值,选项)。这意味着你只能一次设置一个属性,但它看起来像这就是你想要做的。另一种格式为:设置(ATTR,期权),这是你使用的是什么,但不具有字符串键的工作。

无论如何,你不希望直接设置属性为骨干网使用这个钩子在内部做的事情一样提高'改变'的事件。

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);

解决方案

Looking at the backbone source this should already work - your call just needs to look a little different.

saveField : function(field, val){
    //field = 'username'; val = 'Boris'
    model.set(field, val);
}

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 is set(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.

这篇关于设置骨干机型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆