javascript 如何使用 Backbone.js 中的 set 方法更改默认模型属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8244464/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:46:26  来源:igfitidea点击:

How to change default model attributes using set method in Backbone.js

javascriptbackbone.js

提问by Bobbe

I have some defults data in Model

我在模型中有一些默认数据

window.AppState = Backbone.Model.extend({
  defaults: function() {
    return {
      country:  false,
      region: false
    };
  }
});

var appState = new AppState();

Then in Router I get array with new values for model like this:

然后在路由器中,我为模型获取具有新值的数组,如下所示:

[["country", "new country value"], ["region", "new region value"]]

And now in a for loop i cycle to update all received params... I realize it this way

现在在 for 循环中我循环更新所有收到的参数......我是这样意识到的

appState.attributes[arg] = val;

but I think it's not clear, because in documentation of Backbone.js I read about "attribute" method and see this: "Please use set to update the attributes instead of modifying them directly." So my questions is: How i can change attributes of defaults using set method?

但我认为它不清楚,因为在 Backbone.js 的文档中我读到了“属性”方法并看到了这一点:“请使用 set 来更新属性,而不是直接修改它们。” 所以我的问题是:如何使用 set 方法更改默认值的属性?

回答by Sander

try the .set()function...

试试这个.set()功能...

appState.set({arg : val});

once you set the arguments using .set()it will override the default for that.

一旦您使用.set()它设置参数,它将覆盖默认值。

your example modified a bit:

你的例子修改了一点:

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

remarkthis for loop depends a lot on the structure of your array, the way i wrote it will work for the array you gave in your example, should anything change to that you will need to change the working of the for loop

备注此 for 循环在很大程度上取决于数组的结构,我编写它的方式将适用于您在示例中提供的数组,如果对此进行任何更改,您将需要更改 for 循环的工作

remark 2if you use this technique more often, you could always extract that functionality in a helper method.

备注 2如果您更频繁地使用此技术,则始终可以在辅助方法中提取该功能。