Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember transitionToRoute cleanly in a component without sendAction

Tags:

ember.js

How can transitionToRoute be called cleanly from within an Ember component?

It works with injecting a controller into the component and calling the controller's transitionToRoute function, however I'd like something a little more elegant if possible.

What it currently looks like inside the component's javascript:

// this.controller is injected in an initializer
this.controller.transitionToRoute("some.target.route.name");

What would be nicer in the component's javascript:

transitionToRoute("some.target.route.name");

One goal is do this without using sendAction as this particular component has a single purpose and should always transition to the same route. There's no need for any other Ember artifacts to be aware of the route this component always transitions to, there's no need for the associated indirection. The responsibility for the target route is owned by this component.

like image 366
Eliot Sykes Avatar asked Jun 07 '15 19:06

Eliot Sykes


2 Answers



UPDATE Please see the other more recent answers for how to achieve this with less code in newer Ember versions, and vote those up if they work for you - Thanks!



Inject the router into the components and call this.get('router').transitionTo('some.target.route.name').

To inject the router into all components, write an initializer at app/initializers/component-router-injector.js with the following contents:

// app/initializers/component-router-injector.js
export function initialize(application) {
  // Injects all Ember components with a router object:
  application.inject('component', 'router', 'router:main');
}

export default {
  name: 'component-router-injector',
  initialize: initialize
};

Sample usage in a component:

import Ember from 'ember';

export default Ember.Component.extend({
  actions: {
    submit: function() {
      this.get('router').transitionTo('some.target.route.name');
    }
  }
});
like image 190
Eliot Sykes Avatar answered Oct 16 '22 22:10

Eliot Sykes


Jan 22, 2018 update
As of Ember 2.15, phase 1 of the public router service is implemented.
Transition to a route from inside a component:

import { inject as service } from '@ember/service';

export default Ember.Component.extend({
  router: service(),

  actions: {
    someAction() {
        this.get('router').transitionTo('index');
    }
  }

});
like image 13
myartsev Avatar answered Oct 17 '22 00:10

myartsev