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

标签 javascript ember.js ember-components

我正在尝试在 Ember 2.0.1 中实现嵌套组件,但是在使用 toggleProperty 时我遇到了一个奇怪的行为 Action 处理程序中的函数。

第一个组件看起来像:

// ./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 set by comp-1。如果我点击一个按钮,由于函数 this.toggleProperty('prop1') 的执行,文本会变为 Text set by comp-2在操作处理程序中调用 customAction1 .如果我删除此功能或删除 prop1 的设置来自 ./templates/components/comp-2.hbs然后一切都按预期工作,即按钮的文本始终保持为 comp-1 设置的文本。

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

我做错了什么吗?

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

最佳答案

在我看来,您是在通过将两个不同的数据片段绑定(bind)到 init 上的同一属性来制造错误。您正在将 comp-1hello 设置为 Comp-1 设置的文本comp-1 上' s init,并将其绑定(bind)到 comp-2init 上的 d.name

您可能希望 hello 的值只是确定最后的值,然后从那里按预期工作,但是您遇到了双向数据绑定(bind)和绘制的问题之一一个很好的例子,说明为什么 Ember 社区正在远离双向绑定(bind)并拥抱 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 执行切换。

关于javascript - EmberJS : toggleProperty set all properties of a Component to a default value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32363141/

相关文章:

javascript - 如何使用来自其他表单输入的 javascript keyup 函数更新表单的输入值

javascript - 如果数组位于使用 javascript/php 的数组内,则将数组转换为字符串

javascript - css 上的 Jquery 问题

javascript - Ember.js 组件集成测试 : How to work with global injections and nested components?

javascript - 更新或更改或删除/重置 Javascript 事件监听器

ember.js - 迁移到 Ember 辛烷后出现错误

javascript - Ember.JS:Ember 对象及其导出到的位置

ember.js - 如何在 Ember 中检测浏览器

Ember .js 1.13 : The right way to observe a passed-in attribute of component?

css - 避免 Ember 包装我的组件