【发布时间】:2017-12-16 17:14:09
【问题描述】:
我在 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(_(this.attributes).clone())和console.log(_(this.attributes.widgets).clone())看看你会不会得到不同的结果。 -
良好通话 - 通话时为空白
console.log(_(this.attributes).clone()) -
从架构的角度来看,我建议您将
Backbone.Collection用于小部件数组。
标签: javascript arrays backbone.js