将参数传递给Ember triggerAction,它调用带参数的动作

时间:2013-12-03 01:09:22

标签: ember.js handlebars.js

在我的EmberApp中,我有一个视图,在完成某个动作后,会调用另一个“视图”动作。这是一个childView,我基本上这样做:

<button {{action "doSomething"  target="view"}}>DO something</button>

在父视图中,

Ember.View.extend({

   actions:{
       doSomething: function(){
            //perform tasks related to this view
            this.get('childViewName').triggerAction({action:"someAction", target:this.get('childViewName')}) 
       // invoke action that belongs to a child view
      }

});

http://emberjs.com/api/classes/Ember.ViewTargetActionSupport.html#method_triggerAction中指定的子视图传入Ember.TargetActionSupport mixin,并在其自己的操作中具有以下内容:

Ember.ChildView.extend(Ember.ViewTargetActionSupport,{
   actions:{
       someAction:function(){
            console.log("some action called from the Parent view");  // executes fine
       }
     }
 });
});

正如您所知,这段代码按照应有的方式执行。但是,' someAction '实际上会接受参数(模型)。通过提供' this <,可以非常轻松地将此模型提供给我的Handlebars按钮表达式/ strong>'关键字作为参数。

 <button {{action "doSomething" this target="view"}}>DO something</button>

也可以通过简单地声明doSomething接受参数来在'doSomething'acton中检索它,如下所示:

doSomething(modelInstance){
// modelInstance parameter will map to this keyword as specified in the handlebars action 
}

问题是,我不知道如何通过triggerAction调用将此modelInstance或'this'关键字发送到我的ChildView操作。 TriggerAction只接受'action'关键字和docs中提到的target参数。

任何想法/替代解决方案?

1 个答案:

答案 0 :(得分:7)

actionContext将设置动作的this,因此您可以使用它设置动作的这个

doSomething: function(model){
   //perform tasks related to this view
   this.get('childViewName').triggerAction({action:"someAction", target:this.get('childViewName'), actionContext:model}) 
       // invoke action that belongs to a child view
}


someAction:function(){
   console.log(this);  // this would be the model from doSomething
}