1

I have a list of categories. Each category can have sub categories. This is the model I've created:

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

The problem is, if I push a sub category into the subCategories array, it is pushed into every instance of App.Category

Take a look at this jsFiddle.

I don't understand why this is happening, and how should I rewrite this to work properly.


Code:

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);
            }
        };
    }
});

1 Answer 1

2

That's because the hash passed to extend defines the properties on the prototype of the objects that are instantiated by the class. Whereas create define the properties on the instantiated object. There is a very good blog post by Dan Gebhardt about Understanding Ember.js Object. You should check it out.

Your problem can be solved as follows, see http://jsfiddle.net/pangratz666/hXHqs/:

App.Category = Em.Object.extend({
    init: function() {
        this._super();
        this.set('subCategories', Em.ArrayProxy.create({
            content: []
        }));
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.