我在 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)
的行为如下:
- 您调用
console.log(x)
。 x
被转储到控制台。- 继续执行您的
console.log(x)
调用之后的语句。
但事实并非如此,现实更像是这样:
- 您调用
console.log(x)
。 - 浏览器获取对
x
的引用,并将“真实的”console.log
调用排队等待稍后使用。 - 运行(或不运行)各种其他 JavaScript。
- 稍后,来自 (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.attributes
和 this.attributes.widgets
的副本 < strong>(3) 不会干扰您的引用,您会在控制台中看到合理的结果。
这就是这个问题的答案:
It's showing that widgets is not empty when logging
this.attributes
but it's shown as empty when loggingthis.attributes.widgets
. Does anyone know what would cause this?
就潜在问题而言,您可能在某处调用了 fetch
并且您没有考虑其异步行为。解决方案可能是绑定(bind)到 "add"
或 "reset"
事件。
关于javascript - Backbone.js 空数组属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11459244/