10

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

4

4 回答 4

23

这是基于 albertjan 示例的另一种解决方案,适用于您必须在视图中执行一些逻辑然后委托给控制器的情况。这就是我理解你的问题的方式:

哈佛商学院:

<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 正在执行。

于 2013-02-14T09:36:12.177 回答
1

我将在控制器上处理整个事件:

哈佛商学院:

<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.
    }
});                   
于 2013-02-14T08:09:37.937 回答
1

在 Ember 版本 1.0.0 中,我已经成功地将操作添加到控制器中自己的对象文字中。

索引模板.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}}帮助文档

于 2013-09-24T00:10:01.210 回答
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'});
    }
});
于 2014-12-27T05:03:59.507 回答