Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

ember.js - Why won't my tracked array update in Ember Octane?

I'm trying out Octane, and for some reason, if I show an array in a template and I add a new object to it, the UI doesn't update. What am I doing wrong?

Here is my template:

<label for="new-field-name">Field Name</label>
<Input id="new-field-name" @value={{this.newFieldName}} type="text" />
<button {{on "click" this.addField}}>Add field</button>

{{#each this.fields as |field|}}
    <p>{{field.name}}</p>
{{/each}}

And the component:

import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';

export default class ConfigControlsComponent extends Component {
    @tracked fields = []
    @tracked newFieldName = ''

    @action addField() {
        this.fields.push({
            name: this.newFieldName
        })
        console.log(this.fields)
    }
}

The console.log shows the array with the new object added to it, and the fields array is tracked, but nothing changes when I click the button.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you use tracked with arrays, you need to "reset" the array so that Ember notices that there has been a change. Try doing this.fields = this.fields after pushing a new object into the array.

Edit: some linters will guard against self-assignment. So, instead, we could pull from immutability patterns, and set using a new array, as shown below.

export default class ConfigControlsComponent extends Component {
  @tracked fields = []
  @tracked newFieldName = ''

  @action addField() { 
    // add this line
    this.fields = [...this.fields, {
      name: this.newFieldName
    }]; 
  }
}

If you are trying to use tracked with an object instead of an array, you have two options:

First, you could create a class where all the properties on the object are tracked:

import { tracked } from '@glimmer/tracking';

class Address {
  @tracked street;
  @tracked city;
}

class Person {
  address = new Address();

  get fullAddress() {
    let { street, city } = this.address;

    return `${street}, ${city}`;
  }
}

Or, second, you could use the same "reset" approach as the array example above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...