gpt4 book ai didi

javascript - Ember.js - 在对象中定义 ArrayProxy

转载 作者:行者123 更新时间:2023-11-30 18:25:56 26 4
gpt4 key购买 nike

我有一个类别列表。每个类别都可以有子类别。这是我创建的模型:

App.Category = Em.Object.extend({
id: null,
name: null,
subCategories: Em.ArrayProxy.create({content: []})
});

问题是,如果我将子类别推送到 subCategories 数组中,它会推送到 App.Category 的每个实例中

看看这个jsFiddle .

我不明白为什么会这样,我应该如何重写它才能正常工作。


代码:

App.Category = Em.Object.extend({
id: null,
name: null,
subCategories: Em.ArrayProxy.create({content: []})
});

App.categories = Em.ArrayController.create({
content: [],

// assumes list of categories is ordered by parent id
loadCategories: function(cats) {
for (var i=0, cat; i < cats.length; i++) {
var parentID = cats[i].parentID;
delete cats[i].parentID;
cat = App.Category.create(cats[i]);

if (parentID !== null) {
var parent = this.findProperty('id', parentID);
parent.get('subCategories').pushObject(cat);
} else {
this.pushObject(cat);
}
};
}
});

最佳答案

那是因为传递给 extend 的散列定义了由类实例化的对象原型(prototype)的属性。而 create 定义实例化对象的属性。 Dan Gebhardt 有一篇关于 Understanding Ember.js Object 的非常好的博客文章.你应该检查一下。

您的问题可以通过以下方式解决,参见http://jsfiddle.net/pangratz666/hXHqs/ :

App.Category = Em.Object.extend({
init: function() {
this._super();
this.set('subCategories', Em.ArrayProxy.create({
content: []
}));
}
});

关于javascript - Ember.js - 在对象中定义 ArrayProxy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10849423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com