【问题标题】:How do I set an object property within a Backbone model如何在 Backbone 模型中设置对象属性
【发布时间】:2012-04-13 16:19:03
【问题描述】:

是的,所以我有许多 Backbone 模型正在进行中,在其中一个模型中,我有一个具有一组键和值的对象,其中的值是通过从字符串中定位键来修改的。

所以我开始使用基于以下原则构建的代码,我对这段代码输出 true 的方式和原因感到非常满意:

 var boundData = {
     text: 'value' 
 }
 var key = 'text';
 return (boundData[key] === 'value');

所以要设置属性的值,我会这样做:

 boundData[key] = 'new value';

然后我决定将所有现有的类转换为 Backbone 模型。我遇到的问题是,我不能再使用等号运算符更改我的属性,而是使用 Backbone 为模型提供的 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);

希望这对其他人有所帮助!

【问题讨论】:

    标签: javascript backbone.js javascript-framework javascript-objects


    【解决方案1】:

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

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

    希望这对其他人有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-25
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多