observe json object changes in emberjs template

18 Views Asked by At

How to observe json object changes in ember template, here's my test code, I expect to show jsonChange button after I click updateJson, but it didn't

test.hbs

<button {{on "click" this.updateJson}} >updateJson</button>
{{#if this.testJsonChanges}}
<button>jsonChange</button>
{{/if}}

test.js

export default class TestController extends Controller {
  @tracked testjson = {key1:'value1', key2:'value2'};
  @action updateJson() {
    this.testjson.key1 = 'valuex';
  }
    
  get testJsonChanges() {
    return this.testjson.key1 != 'value1';
  }
}
1

There are 1 best solutions below

0
NullVoxPopuli On BEST ANSWER

@tracked only applies to references, much like const is only constant on references -- if you want changes of properties to be tracked, you'll need to use TrackedObject

import { TrackedObject } from 'tracked-built-ins';

export default class TestController extends Controller {
  testjson = new TrackedObject({key1:'value1', key2:'value2'});

  @action updateJson() {
    this.testjson.key1 = 'valuex';
  }
    
  get testJsonChanges() {
    return this.testjson.key1 != 'value1';
  }
}