EmberJS:toggleProperty将Component的所有属性设置为默认值

时间:2015-09-02 21:08:48

标签: javascript ember.js ember-components

我正在尝试在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创建两个名称​​文本由comp- 1 设置的按钮。如果我单击一个按钮,文本将变为由comp- 2 设置的文本,因为执行了在动作处理程序中调用的函数this.toggleProperty('prop1') { {1}}。如果我删除此功能或从customAction1删除prop1的设置,那么一切都按预期工作,即按钮文本始终为文本设置为comp- 1

为什么./templates/components/comp-2.hbs功能会设置其他属性?

我做错了吗?

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

1 个答案:

答案 0 :(得分:0)

在我看来,您通过将两个不同的数据绑定到Invoke Standalone SonarQube Analysis上的同一属性来创建错误。您在init的{​​{1}}上将comp-1的{​​{1}}设置为hello,并在{{1}上将其绑定到Text set by comp-1 } comp-1

您可能期望init的值只能解决最后的问题然后按预期工作,但是您遇到了双向数据绑定的问题并绘制了一个很好的示例为什么Ember社区正在摆脱双向约束并拥抱DDAU

我认为这只是你偶然发现的事情,因为我无法想象这种情况会在野外发生,但为了以防万一,请使用d.name

comp-2

然后在init的模板中使用hello代替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'); } } }); 中的按钮在{{readOnlyHello}}中切换{{hello}},则还应在此处关注DDAU。您最多可以发送comp-1的操作,并让d.bool执行切换。

相关问题