2013-02-14 66 views
10

控制器動作我有一個onClick查看事件提交按鈕。這個事件檢查一個標誌,並根據條件允許表單提交。我想叫控制器上的submit行動。做這個的最好方式是什麼?從調用視圖灰燼

回答

23

這裏基於由albertjan爲例如另一種解決方案你必須在View和After之後執行一些邏輯吃了你的控制器。這是我理解你的問題的方式:

HBS:

<script type="text/x-handlebars" data-template-name="index"> 
    <button {{action submit target="view"}} >Sumbit</button> 
</script> 

查看:

App.ThingView = Ember.View.extend({ 
    submit : function(){ 
      //do the view part of your logic 
     var object = //do whatever you may need 
     this.get("controller").send("submitInController", object); //you do not have to send object, if you do not need to 
    } 
}); 

控制器:

App.ThingController = Em.ObjectController.extend({ 
    submitInController: function(model) { 
     // do the controller part of your logic 
    } 
}); 

注:從您的視圖呼叫也會冒泡到您當前的路線。所以這基本上是相同的代碼,即燼使用動作助手時執行。

1

我將處理控制器上的整個事件:

HBS:

<script type="text/x-handlebars" data-template-name="index"> 
    <button {{action "submit"}}>Sumbit</button> 
</script> 

控制器:

App.ThingController = Em.ObjectController.extend({ 
    submit: function() { 
     //handle things here! 
     //change the state of your object here to reflect the changes that 
     //the submit made so that the view shows these. 
    } 
});     
+0

這不可能在這裏 – bcardarella 2013-02-14 14:59:46

+0

爲什麼在這裏不可能?你能解釋一下嗎? – albertjan 2013-02-14 17:25:21

+1

可能提交需要一些DOM相關的東西,該控制器不能(容易)見。 – DRobinson 2013-09-30 20:49:37

1

在餘燼版本1.0.0,我一直有成功加入行動,以自己的對象在控制器中文字。

IndexTemplate.html

<script type="text/x-handlebars" data-template-name="index"> 
    <button {{action "submit"}}>Submit</button> 
</script> 

ThingController.js

App.ThingController = Ember.ObjectController.extend({ 
    actions: { 
     submit: function() { 
      //handle things here! 
      //change the state of your object here to reflect the changes that 
      //the submit made so that the view shows these. 
     } 
    } 
}); 

欲瞭解更多信息,請從灰燼指南中的{{action}} helper documentation

0

如果視圖使用ViewTargetActionSupport mixin,則可以從視圖中觸發操作。以下示例演示了它的用法:

App.SomeController = Ember.Controller.extend({ 
    actions: { 
     doSomething: function() { 
      alert('Doing something!'); 
     } 
    } 
}); 

App.SomeView = Ember.View.extend(Ember.ViewTargetActionSupport, { 
    someMethod: function() { 
     this.triggerAction({action: 'doSomething'}); 
    } 
});