【问题标题】:Ember this.set in componentEmber this.set 在组件中
【发布时间】:2018-06-13 13:50:21
【问题描述】:

我似乎对 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

【问题讨论】:

  • 我觉得这个问题有点混乱:dup 代码是怎么回事……这有关系吗?谁在打电话给change?我尝试使change 成为一个动作并添加一个按钮来调用它,并使用{{input... 帮助器对value 进行正确的双向绑定...但随后取消注释hello 行也没有效果。
  • 我想我没有更新 twiddle。我需要更改名称并更改一些我正在使用的实际代码来创建旋转。希望它应该被更新。基本上我需要将change 函数中的变量设置为init 中设置的变量的值。
  • 仍然无法重现问题。如果我将 this.set('value','something else'); 添加到 init 方法(否则整个旋转的值是 'initial value'),然后输入,输入然后离开输入字段导致它按预期重置为 'initial value'(或 @ 987654338@ 如果相应的行未注释)。

标签: ember.js render init ember-components


【解决方案1】:

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

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

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

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

它只能执行一次,因为值仅更改 1 次。 (在第一次将值更改为字符串时)

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

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

Twiddle for reference

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      • 2016-08-26
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      相关资源
      最近更新 更多