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

Bob*_*bbe 2 javascript backbone.js

我在模型中有一些defults数据

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

var appState = new AppState();
Run Code Online (Sandbox Code Playgroud)

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

[["country", "new country value"], ["region", "new region value"]]
Run Code Online (Sandbox Code Playgroud)

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

appState.attributes[arg] = val;
Run Code Online (Sandbox Code Playgroud)

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

San*_*der 9

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

appState.set({arg : val});
Run Code Online (Sandbox Code Playgroud)

一旦你使用.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());
Run Code Online (Sandbox Code Playgroud)

注意 这个for循环在很大程度上取决于你的数组的结构,我写它的方式将适用于你在你的例子中给出的数组,如果有任何改变,你将需要改变for循环的工作

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