Ember this.set in component

时间:2018-01-03 20:54:04

标签: ember.js render init ember-components

我似乎对Ember组件的init属性做错了。

我的代码看起来像这样。

import Ember from 'ember';

export default Ember.Component.extend({
  init(){
    this._super(...arguments);
    this.set('initial_value', this.get('value'));
  },

  change(e){
    console.log('value should be reset to ' + this.get('initial_value')) //This prints the initial value correctly.
    this.set('value', this.get('initial_value')); // this line does not update value.
    //this.set('value', 'hello'); //this line does update value.   
  }
});

为什么我可以使用字符串文字更新value但不能使用this.get('initial_value')更新?

我尝试了这段代码,为组件生命周期中的每个函数换出init。我这样做是因为我认为它与渲染有关;还是那样。

这是twiddle

2 个答案:

答案 0 :(得分:1)

由于您使用了<input type="text" value={{value}}>,因此它的单向绑定。即,在更改组件中的value时,更改将反映在输入框中,但更改输入框中的值不会更改组件中变量value的值。

在Ember中,只有当组件中变量的值发生变化时,DOM才会更新。在my-component.js中,变量value的值不会发生变化。它只包含字符串文字initial value

例如,this.set('value', Math.random());这将在变量value的值发生变化时起作用。

  

为什么我可以使用字符串文字更新值,但不能使用this.get(&#39; initial_value&#39;)更新?

     

只能进行一次,因为值只会改变1次。 (在第一次将值更改为字符串时)

要实现您的案例, 您可以使用实现双向绑定的{{input value=value}}。编辑输入框时,变量value的值会发生变化。

在聚焦时,this.set('value',this.get('initial_value'))将根据需要设置初始值。

Twiddle for reference

答案 1 :(得分:0)

您可以在my-component.hbs文件中包含{{input value=value}},当您更改输入时,它将在输入助手中调用change函数,该函数将调用组件的change函数。将其重置为initial_value

相关问题