我正在尝试在 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-1
的 hello
设置为 Comp-1 设置的文本
在 comp-1
上' s init
,并将其绑定(bind)到 comp-2
的 init
上的 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/