toggleProperty将组件的所有属性设置为默认值

EmberJS: toggleProperty set all properties of a Component to a default value

本文关键字:属性 设置 默认值 组件 toggleProperty      更新时间:2023-09-26

我试图在Ember 2.0.1中实现嵌套组件,但是当在动作处理程序中使用toggleProperty函数时,我得到了一个奇怪的行为。

第一个组件看起来像:

// ./components/comp-1.js
import Ember from 'ember';
export default Ember.Component.extend({
  prop1: false,
  hello: "Default text of comp-1",
  _changeHello: function() {
    this.set('hello', 'Text set by comp-1');
  }.on("init"),
  actions: {
    customAction1() {
      this.toggleProperty('prop1');
    }
  }
});

.

// ./templates/components/comp-1.hbs
<button {{action 'customAction1'}}>{{hello}}</button>

第二个是:

// ./components/comp-2.js
import Ember from 'ember';
export default Ember.Component.extend({
  data: [],
  _doSomeImportentStuff: function() {
    var data = this.get('data');
    data = [{name: 'Text set by comp-2', bool: false}, 
            {name: 'Text set by comp-2', bool: true}];
    this.set('data', data);
  }.on("init")
});

.

// ./templates/components/comp-2.hbs
{{#each data as |d|}}
{{comp-1 hello=d.name prop1=d.bool}}
{{/each}}

组件comp-2创建了两个名称为的按钮。Text由comp-1设置。如果我单击一个按钮,文本更改为由comp-2设置的文本,因为在动作处理程序customAction1中调用的函数this.toggleProperty('prop1')的执行。如果我删除此功能或从./templates/components/comp-2.hbs中删除prop1的设置,那么一切都按预期工作,即按钮的文本始终保持为 comp-1设置的文本。

为什么toggleProperty函数会设置其他属性?

我做错了什么吗?

在操作的行为可以在这里看到:http://ember-twiddle.com/90798b4952deb4a83de1

在我看来,你通过将两个不同的数据块绑定到init上的相同属性来创建一个bug。您将comp-1hello设置为comp-1init上的Text set by comp-1,并将其绑定到comp-2init上的d.name

你可能期望hello的价值只是解决最后的问题,然后从那里开始工作,但你遇到了一个双向数据绑定的问题,并描绘了一个很好的例子,为什么Ember社区正在远离双向绑定并拥抱DDAU。

我认为这只是你偶然发现的,因为我无法想象这种情况在野外发生,但以防万一,使用Ember.computed.oneWay:

export default Ember.Component.extend({
  prop1: false,
  readOnlyHello: Ember.computed.oneWay('hello'),
  _changeHello: function() {
    this.set('readOnlyHello', 'Text set by comp-1');
  }.on("init"),
  actions: {
    customAction1() {
      this.toggleProperty('prop1');
    }
  }
});

comp-1的模板中使用{{readOnlyHello}}代替{{hello}}

如果你需要将comp-2中的d.boolcomp-1中的按钮切换,你也应该遵循这里的DDAU。您将发送一个动作到comp-2,并让comp-2执行切换。