Reputation: 2496
I want to define a reactive array property in a component so that every time the array is updated, it auto-updates necessary HTML content.
I thought this was going to be straightforward, but it didn't work as I expected. Every time I retrieve the property via this.get('array')
, it returns undefined
.
// components/test-component.js
export default Ember.Component.extend({
_array: [],
array: Ember.computed('_array',{
get(key) { return this.get('_array'); },
set(key,value) { this.set('_array', value); }
}),
isEmpty: Ember.computed('array', function() {
// Here, this.get('array') returns undefined. Why?
return this.get('array').length;
}),
actions: {
addNew() {
this.get('array').push(Date.now());
}
},
init() {
this._super(...arguments);
this.set('array', [1,2,3]);
},
});
I also noticed that in the init
method, if I retrieve the array property right after setting it, it also returns undefined
. Why is this happening?
Here is a twiddle. It is supposed to iterate the array, and show a list of all items, but it is currently crashing because it returns undefined.
Upvotes: 0
Views: 382
Reputation: 53981
The problem you are currently seeing is that you need to add a return
in the set
method. Also you should use the Ember.computed('array.[]')
syntax where you listen for changes to the array itself.
But you would be better off using an Ember array so that you don't need a second array:
import Ember from 'ember';
export default Ember.Component.extend({
array: undefined,
init() {
this._super(...arguments);
this.set('array', Ember.A());
},
actions: {
addNew() {
this.get('array').addObject(Date.now());
}
}
});
and
<ul>
{{#each array as |item|}}
<li>{{item}}</li>
{{else}}
<li>No items</li>
{{/each}}
</ul>
<button onclick={{action 'addNew'}}>Add New</button>
Upvotes: 2