Ember.js Router Action to Controller

Lux picture Lux · Jun 15, 2012 · Viewed 7.9k times · Source

When I use the Ember Router, how can I define actions in the template who are connected to the controller?

An Example is here: http://jsfiddle.net/KvJ38/3/

Unter My Profile are two actions: One is defined on the State, and is working Two is defined on the Controller. How can i make this working or should I use another approach?

App.Router = Em.Router.extend({
  enableLogging: true,
  location: 'hash',

  root: Em.State.extend({
    // EVENTS
    goHome: Ember.State.transitionTo('home'),
    viewProfile: Ember.State.transitionTo('profile'),

    // STATES
    home: Em.State.extend({
      route: '/',
      connectOutlets: function(router, context) {
        var appController = router.get('applicationController');
        appController.connectOutlet(App.HomeView);
      }
     }),

    // STATES
    profile: Em.State.extend({
      route: '/profile',
        connectOutlets: function(router, context) {
          var appController = router.get('applicationController');
          appController.connectOutlet(App.ProfileView);
        }
    }),

    one: function() {
      alert("eins");
    },
  }) 
});

Answer

Stéphane Blond picture Stéphane Blond · Jun 15, 2012

The default target of an action is the router, but you can define another one in the template:

{{action two target="controller"}}

And add a "two" function in "App.ProfileController".

UPDATE

This answer was hopefully correct mid 2012. Now (September 2014), the documentation says:

By default, the {{action}} helper triggers a method on the template's controller. [...] If the controller does not implement a method with the same name as the action in its actions object, the action will be sent to the router, where the currently active leaf route will be given a chance to handle the action. [...] If neither the template's controller nor the currently active route implements a handler, the action will continue to bubble to any parent routes. Ultimately, if an ApplicationRoute is defined, it will have an opportunity to handle the action. When an action is triggered, but no matching action handler is implemented on the controller, the current route, or any of the current route's ancestors, an error will be thrown.