emberjs动作上下文绑定到子组件视图而不是组件

时间:2015-06-15 23:15:52

标签: ember.js

我正在尝试使用sendAction从子组件传递操作。我的操作按预期在父组件上执行,但是,this指的是孩子的view对象的上下文。

请参阅下面的组件和组件模板:

父组件模板

// 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
      }
    }
  });

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

你可以尝试

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

在您的代码中this.sendAction('select', this)表示将组件对象传递给父组件,因此下一步行为看起来很奇怪。

相关问题