javascript - Backbone.js 空数组属性

标签 javascript arrays backbone.js

我在 Backbone.js 模型中遇到了一个奇怪的问题,其中数组成员显示为空白。它看起来像这样:

var Session = Backbone.Model.extend({
    defaults: {
        // ...
        widgets: []
    },
    addWidget: function (widget) {
        var widgets = this.get("widgets");

        widgets.push(widget);
        this.trigger("change:widgets", this, widgets);
    },
    // ...
    // I have a method on the model to grabbing a member of the array
    getWidget: function (id) {
        console.log(this.attributes);
        console.log(this.attributes.widgets);

        // ...
    }
});

然后我通过 addWidget 添加一个小部件。当尝试 getWidget 我得到的结果(在 Chrome 中)是这样的:

Object
    widgets: Array[1]
        0: child
        length: 1
        __proto__: Array[0]
    __proto__: Object
[]

当记录 this.attributes 时显示小部件不为空,但在记录 this.attributes.widgets 时显示为空。有谁知道这会导致什么?

编辑 我更改了模型以在初始化方法中实例化小部件数组以避免跨多个实例的引用,并且我开始使用 backbone-nested没有运气。

最佳答案

在信任控制台时要小心,异步行为通常会让你误入歧途。

您期望 console.log(x) 的行为如下:

  1. 您调用 console.log(x)
  2. x 被转储到控制台。
  3. 继续执行您的 console.log(x) 调用之后的语句。

但事实并非如此,现实更像是这样:

  1. 您调用 console.log(x)
  2. 浏览器获取对 x 的引用,并将“真实的”console.log 调用排队等待稍后使用。
  3. 运行(或不运行)各种其他 JavaScript。
  4. 稍后,来自 (2)console.log 调用将 x 的当前状态转储到控制台中,但这 x 不一定与 x 匹配,因为它在 (2) 中。

在您的情况下,您正在这样做:

console.log(this.attributes);
console.log(this.attributes.widgets);

所以你在 (2) 有这样的东西:

         attributes.widgets
             ^         ^
             |         |
console.log -+         |
console.log -----------+

然后 (3) 中发生了一些事情,它有效地执行了 this.attributes.widgets = [...](即更改 attributes.widget 引用)所以,当 (4) 出现时,您将得到:

         attributes.widgets // the new one from (3)
             ^
             |
console.log -+
console.log -----------> widgets // the original from (1)

这让您看到了两个不同版本的 widgets:新的在 (3) 中收到了一些东西,而原始的是空的。

当你这样做时:

console.log(_(this.attributes).clone());
console.log(_(this.attributes.widgets).clone());

您正在获取附加到 console.log 调用的 this.attributesthis.attributes.widgets 的副本 < strong>(3) 不会干扰您的引用,您会在控制台中看到合理的结果。

这就是这个问题的答案:

It's showing that widgets is not empty when logging this.attributes but it's shown as empty when logging this.attributes.widgets. Does anyone know what would cause this?

就潜在问题而言,您可能在某处调用了 fetch 并且您没有考虑其异步行为。解决方案可能是绑定(bind)到 "add""reset" 事件。

关于javascript - Backbone.js 空数组属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11459244/

相关文章:

javascript - 简单的 backbone.js 问题

javascript - 使用另一个 Controller 中的模型过滤一个 Controller 的内容(AngularJS)

javascript - 使用 jQuery 在 div 中淡入淡出

javascript - 考虑到网络延迟,如何确定 HTTP 请求的准确发送时间?

javascript - Array.push() 方法在 Javascript 中是如何工作的?

javascript - 了解如何结合使用 require js 和 text js 在主干应用程序中加载 html 模板

javascript - ng build --prod 给我一个错误

java - 原始数组与集合

python - numpy 数组内给定值的凸包 - python 2.7

javascript - 事件在 Backbone.js 上不起作用