2015-06-15 48 views
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 
     } 
    } 
    }); 

有什麼建議嗎?

回答

0

你可以嘗試

handleAction: function() { 
    // ... 
    this.sendAction('select', this.get('name')); // this.get('name') instead of this 
} 

在您的代碼this.sendAction('select', this)手段傳遞組件對象到父組件,所以接下來的行爲看起來很奇怪。

+0

你說得對。將「this」傳遞給我的動作負載應該是代碼異味的第一個標誌。 –

相關問題