Javascript 如何在主干模型中设置对象属性

Javascript 如何在主干模型中设置对象属性,javascript,backbone.js,javascript-framework,javascript-objects,Javascript,Backbone.js,Javascript Framework,Javascript Objects,好的,我有很多主干模型,其中一个我有一个对象,它有一组键和值,其中的值是通过从字符串中定位键来修改的 因此,我从基于以下原则构建的代码开始,我非常熟悉该代码将如何以及为什么输出true: var boundData = { text: 'value' } var key = 'text'; return (boundData[key] === 'value'); 因此,要设置属性的值,我将执行以下操作: boundData[key] = 'new value'; 然后我

好的,我有很多主干模型,其中一个我有一个对象,它有一组键和值,其中的值是通过从字符串中定位键来修改的

因此,我从基于以下原则构建的代码开始,我非常熟悉该代码将如何以及为什么输出true:

 var boundData = {
     text: 'value' 
 }
 var key = 'text';
 return (boundData[key] === 'value');
因此,要设置属性的值,我将执行以下操作:

 boundData[key] = 'new value';
然后我决定将所有现有的类转换为主干模型。我遇到的问题是,我不能再使用equals运算符更改属性,而是使用主干为模型提供的set方法。此方法将字符串作为第一个参数,此字符串标识我试图更改的变量的键

 this.set("boundData[" + settings.name + "]", new OpenCore.boundData(settings));
这似乎不起作用,这也不起作用:

 this.set("boundData." + settings.name, new OpenCore.boundData(settings));

解决了。当我写这个问题的时候,我想出了一个办法。但我想我会把它留在这里,以防其他人遇到同样的问题


这是一个解决方案,虽然它可能不是最好的(如果有人能把原来的方法分类,我会感兴趣),但它似乎是可行的

var boundData = this.get('boundData'); //Create a reference of the object with get().
boundData[settings.name] = new OpenCore.boundData(settings); //Update this reference.
//The change will be reflected in the original instance or you can just:
this.set('boundData', boundData);
var boundData = this.get('boundData'); //Create a reference of the object with get().
boundData[settings.name] = new OpenCore.boundData(settings); //Update this reference.
//The change will be reflected in the original instance or you can just:
this.set('boundData', boundData);

希望这对其他人有帮助

这是一个解决方案,虽然它可能不是最好的(如果有人能将原始方式排序,我会感兴趣),但它似乎有效

var boundData = this.get('boundData'); //Create a reference of the object with get().
boundData[settings.name] = new OpenCore.boundData(settings); //Update this reference.
//The change will be reflected in the original instance or you can just:
this.set('boundData', boundData);
var boundData = this.get('boundData'); //Create a reference of the object with get().
boundData[settings.name] = new OpenCore.boundData(settings); //Update this reference.
//The change will be reflected in the original instance or you can just:
this.set('boundData', boundData);
希望这对其他人有帮助