10
votes

I have a submit button with a onClick view event. This event checks a flag and depending upon the condition it will allow form submission. I'd like the submit action on the controller to be called. What is the best way to do this?

4

4 Answers

23
votes

Here another solution based on the example by albertjan for the case you have to perform some logic in your View and afterwards delegate to your controller. This is the way i understood your question:

HBS:

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

View:

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

Controller:

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

Note: The call from your view will also bubble up to your current route. So this is basically the same code, that ember is executing when using the action helper.

1
votes

I would handle the whole event on the controller:

HBS:

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

Controller:

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.
    }
});                   
1
votes

In Ember version 1.0.0, I've been having success adding actions to their own object literal in the controller.

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

For more information, check out the {{action}} helper documentation from Ember Guides.

0
votes

You can trigger an action from a view if the view uses the ViewTargetActionSupport mixin. The following example demonstrates its usage:

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

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