【问题标题】:EmberJS: toggleProperty set all properties of a Component to a default valueEmberJS:toggleProperty 将组件的所有属性设置为默认值
【发布时间】:2015-09-02 21:08:47
【问题描述】:

我正在尝试在 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 设置的文本,因为执行了在动作处理程序 customAction1 中调用的函数 this.toggleProperty('prop1') .如果我删除此功能或从 ./templates/components/comp-2.hbs 中删除 prop1 的设置,那么一切都会按预期工作,即按钮的文本始终保持为 由 comp-1设置的文本>.

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

我做错了吗?

可以在此处查看实际行为:http://ember-twiddle.com/90798b4952deb4a83de1

【问题讨论】:

  • 这方面有什么成功吗?

标签: javascript ember.js ember-components


【解决方案1】:

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

您可能期望 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-1 中的按钮在comp-2 中切换d.bool,您也应该在此处关注DDAU。您可以向comp-2 发送一个操作,然后让comp-2 执行切换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2016-07-04
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多