【问题标题】:Backbone model property getting updated on update of another property骨干模型属性随着另一个属性的更新而更新
【发布时间】:2016-01-29 21:06:51
【问题描述】:

这是我的模型:

var SendAlertsModel = Backbone.Model.extend({

            defaults: {
                customSubject: "",
                customNote: "",
                userList:[],
                alertUserList:[]
            }

        });

内景:

initialize: function(options) {
                var self= this;
                if(_.isUndefined(options)===false){
                    self.model= new SendAlertsModel();
                    self.loggedInUser = app.user;
                    self.model.set("userList",options.previousTabData.get("userList"));
                    self.model.set("alertUserList",options.previousTabData.get("userList"));
                    self.model.get("alertUserList").push(self.loggedInUser);
                }
            },

我在这里面临的问题是,当我将 loggedInUser 推送到 alertUserList 数组时,它会自动将相同的 loggedInUser 推送到 userList 数组。

请对此提出您的建议。

谢谢

【问题讨论】:

  • @nikoshr 你能分享适当的链接吗?谢谢
  • 我将您的问题作为stackoverflow.com/a/34951015/1071630 的副本结束了,但这可能是一个错误
  • 谢谢.. 不是问题
  • 我认为你不需要 var self = this;在这种情况下,因为您没有在 if 块中更改上下文。
  • 但这应该不是问题@Rupert

标签: javascript backbone.js backbone-views backbone-model


【解决方案1】:
//create new alerts model
model = new SendAlertsModel();

//assign logged in user to local variable
loggedInUser = app.user;

//set the user list to be the user list from the previous tab data
model.set("userList",options.previousTabData.get("userList"));  

//set the alertUserList to be the previous tab user list by reference
model.set("alertUserList",options.previousTabData.get("userList"));

//push the logged in user into the alert user list
model.get("alertUserList").push(self.loggedInUser);

我认为当您将 alertUserList 设置为 userList 时会出现问题。由于用户列表是一个对象,alertUserList 现在包含对 userList 的引用。这不是副本。当您更新 alertUserList 时,实际上您也在更新 userList。

这样想:

var alertUserList = userList = {some object in memory};

在此行中,您需要创建一个副本:

model.set("alertUserList",options.previousTabData.get("userList"));

我不确定 userList 是什么数据类型,所以这取决于它。如果您只需要一个浅拷贝,那么您可以使用下划线/lodash 库来执行此操作(我假设这就是“_”):

model.set("alertUserList",_.clone(options.previousTabData.get("userList")));

【讨论】:

  • userList 是来自上一个选项卡的用户列表。我还需要显示登录用户。所以我在模型中创建了一个名为 alertUserList 的新属性,我将登录用户推送到网格上。但我也需要原始用户列表。所以我将它保存在 userList 中。是的,你是对的,我只是在这里创建引用,这就是它更新 userList 属性的原因
  • 也许在您的模型上为原始列表创建一个名为“userList”的属性,并在“alertUserList”属性中放置一个克隆。
  • 我确实克隆了,但它添加了很多不需要的属性。有没有办法只保留原始属性?
  • 你可以使用下划线的pick方法:underscorejs.org/#pick并指定你想要的属性。
  • 用函数替换defaults也是个好主意,在默认值中包含可变值(例如数组)只是自找麻烦。
猜你喜欢
  • 2016-02-22
  • 2020-02-21
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多