Ember.js: Array property value shared between instances of a Component

Created on 11 Dec 2013  ·  3Comments  ·  Source: emberjs/ember.js

Not quite sure if I've done something wrong, but here it is.
I've made a component with some properties, all of them working correctly in the scope of their component instance. However when I added a property with an array value, it behaves unexpectedly: When an element is pushed into the array of a component via @set, it is pushed into the property of each component.

Most helpful comment

I assume you've got something like:

App.MyThingsComponent = Ember.Component.extend({
  things: []
}):

This will use the same instance of the array for all components because it's evaluated when the class is defined, not when it's instantiated.

You can fix this by instantiating the array when the component is initialized:

App.MyThingsComponent = Ember.Component.extend({
  things: null,
  setupThings: function(){
    this.set("things", []);
  }.on("init")
}):

Now you'll get a new array instance for each component instance and things should behave as you expect.

hth

All 3 comments

I assume you've got something like:

App.MyThingsComponent = Ember.Component.extend({
  things: []
}):

This will use the same instance of the array for all components because it's evaluated when the class is defined, not when it's instantiated.

You can fix this by instantiating the array when the component is initialized:

App.MyThingsComponent = Ember.Component.extend({
  things: null,
  setupThings: function(){
    this.set("things", []);
  }.on("init")
}):

Now you'll get a new array instance for each component instance and things should behave as you expect.

hth

Thanks a lot! So is this intended behavior? How come it doesn't work this way with strings for example?

@Geokoumpa this is due to Javascript's prototypal inheritance. Here is thorough blog post from @wycats that is useful to learn about that aspect of Javascript.

http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/

Was this page helpful?
0 / 5 - 0 ratings