我在模型中有一些默认数据
window.AppState = Backbone.Model.extend({
defaults: function() {
return {
country: false,
region: false
};
}
});
var appState = new AppState();
然后在 Router 中,我得到包含模型新值的数组,如下所示:
[["country", "new country value"], ["region", "new region value"]]
现在在 for 循环中我循环更新所有接收到的参数... 我是这样理解的
appState.attributes[arg] = val;
但我认为这还不清楚,因为在 Backbone.js 的文档中我读到了“属性”方法并看到了这个: “请使用 set 来更新属性,而不是直接修改它们。” 所以我的问题是:如何使用 set 方法更改默认值的属性?
最佳答案
试试 .set()
函数...
appState.set({arg : val});
一旦您使用 .set()
设置参数,它将覆盖默认值。
你的例子修改了一下:
window.AppState = Backbone.Model.extend({
defaults: function() {
return {
country: false,
region: false
};
}
});
var appState = new AppState();
// when you get your array of new values you can turn it in an object
var myArray = [["country", "new country value"], ["region", "new region value"]];
var newValues = {};
for (var i = 0; i < myArray.length; ++i)
{
newValues[myArray[i][0]] = myArray[i][1];
}
// set the properties to the new values
appState.set(newValues);
// if you now return the json of the model, it has changed properties
console.log(appState.toJSON());
备注 这个 for 循环在很大程度上取决于您的数组结构,我编写它的方式将适用于您在示例中提供的数组,如果有任何更改,您将需要更改 for 循环的工作
备注2 如果您更频繁地使用此技术,则始终可以在辅助方法中提取该功能。
关于javascript - 如何使用 Backbone.js 中的 set 方法更改默认模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8244464/