Subclassing components help

Hi,

I’m fairly new to EmberJS, so hopefully this is a fairly easy question to answer. I’m trying to learn how to use Components, and I’m running into an issue with subclassing them.

What I created is a base Component class, and then another class that extends that class. The base Component (MyBaseComponent) has a property (‘foo’) which is an object. I also have a new Component (MyNewComponent) which extends MyBaseComponent, and upon initialization, it modifies a property of ‘foo’. However, I’m doing something wrong, because when I modify ‘foo’, it modifies it for all instances of MyNewComponent. And I don’t know why that is.

Working example:

Here’s how I have my Components set up:

App.MyBaseComponent = Ember.Component.extend({
    foo: {
        bar: 'base',
        anotherProperty: 'wacka'
    }
});

App.MyNewComponent = App.MyBaseComponent.extend({
    init: function() {
        this._super();
        var title = this.get('title');
        this.set('foo.bar', title);
    }
});

The template:

<script type="text/x-handlebars" id="components/my-new">
    foo.bar (App.MyNewComponent) is: {{foo.bar}}<br/>
</script>

And how I’m calling my component:

{{my-new title="instance1"}}
{{my-new title="instance2"}}

Again, I’m new to EmberJS, and my understanding is quite limited, so any help would be much appreciated!

This is actually a JavaScript problem, not Ember specific. When you do:

App.MyBaseComponent = Ember.Component.extend({
    foo: {
        bar: 'base',
        anotherProperty: 'wacka'
    }
});

You’re giving it a property foo with a reference to an object, but one which is shared by everything that uses it as it is created at compile time and not at runtime. You need to move the initialization to be done when the object is created:

App.MyBaseComponent = Ember.Component.extend({
    init: function() {
        this._super();
        this.set( 'foo', {
            bar: 'base',
            anotherProperty: 'wacka'
        });
    }
});

A similar approach is needed for any object in JavaScript where you don’t want the object shared across all instances.

Thank you! I kinda figured something like that was going on, but not the specifics.