0
我試圖通過sendAction
從子組件傳遞操作。我的動作按預期在父組件上執行,但是,this
改爲引用兒童的view
對象的上下文。emberjs操作上下文綁定到子組件視圖而不是組件
請參閱以下的組件和組件的模板:
父組件模板
// templates/components/parent.hbs
<div class="parent">
{{child name="Stewie" select="selectChild"}}
{{child name="Molly" select="selectChild"}}
</div>
{{yield}}
子組件模板
// templates/components/child.hbs
<div class="child" {{action "handleAction" on="click"}}>
name: {{name}}
</div>
{{yield}}
子組件
// components/child.js
import Ember from 'ember';
export default Ember.Component.extend({
selected: false,
actions: {
handleAction: function() {
this.set('selected', !this.get('selected'));
this.sendAction('select', this);
}
}
});
父組件
// components/parent.js
import Ember from 'ember';
export default Ember.Component.extend({
selectedChildren: [],
actions: {
selectChild: function(child) {
// oops! this is bound to the child's view isntead of this parent component
var selectedChildren = this.get('selectedChildren');
// undefined
selectedChildren.pushObject(child);
// oops! cannot call pushObject of undefined
}
}
});
有什麼建議嗎?
你說得對。將「this」傳遞給我的動作負載應該是代碼異味的第一個標誌。 –