copenndthagen
copenndthagen

Reputation: 50732

Ember dynamically update template (array item)

I am using Ember version 2 and have my component template as below;

{{#each info as |item|}}
    <span class="value">{{item.value}}</span>
    <span class="label">{{t item.label}}</span>
{{/each}}

Now I want to write values to it dynamically (i.e. assume it is a dynamic total which initially is 0 & updates automatically based on user selection of some rows)

My question is while the below code works;

var info = self.get('gridParas.info');
info.popObject();
info.pushObject({
    label: 'MyTotalField',
    value: total
});
self.set('gridParas.info', info);

This does not work;

var info = self.get('gridParas.info');
info.label = "MyTotalField";
info.value = total;
self.set('gridParas.info', info);

Is the popObject(), pushObject() the correct way ? What is wrong with the 2nd approach ? I wanted to avoid pop, push each time.

Upvotes: 0

Views: 248

Answers (2)

user663031
user663031

Reputation:

You can set the properties directly on the last element, without popping and pushing:

var info = self.get('gridParas.info');
info.getObjectAt(info.get('length') - 1).setProperties({
  label: 'MyTotalField',
  value: total
});

Or, if you don't want to reuse the current last item, use replace:

info.replace(info.get('length') - 1, 1, [{
  label: 'MyTotalField',
  value: total
}]);

As you can see, you need to pass replace the index, the count of items to be replaced, and an array of new items to stick in there.

In any case, you do not need this:

self.set('gridParas.info', info);

Because that's already gridParas.info's value.

Upvotes: 0

Jordan Morano
Jordan Morano

Reputation: 66

the set() methods notifies the model that a property has changed, triggering the template to update. Instead of using it, you can call notifyPropertyChange('info') or notifyPropertyChange('info.label') after you update the label and value, which should update the template. More info can be found in the docs here:

http://emberjs.com/api/classes/Ember.Observable.html#method_notifyPropertyChange

Upvotes: 0

Related Questions