从Ember中的视图调用控制器操作

时间:2013-02-14 06:28:42

标签: ember.js

我有一个带有onClick观看事件的提交按钮。此事件检查标志,并根据条件允许表单提交。我希望调用控制器上的submit操作。这样做的最佳方式是什么?

4 个答案:

答案 0 :(得分:23)

这是基于albertjan示例的另一种解决方案,您需要在View中执行某些逻辑,然后委托给您的控制器。这是我理解你的问题的方式:

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

注意:您视图中的来电也会冒泡到您当前的路线。所以这基本上是相同的代码,ember在使用动作助手时正在执行。

答案 1 :(得分: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.
    }
});                   

答案 2 :(得分:1)

在Ember版本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.
        }
    }
});

有关详细信息,请查看Ember Guides中的{{action}} helper documentation

答案 3 :(得分: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'});
    }
});