简体   繁体   中英

How to access controller from route in Ember?

Is there any foolproof way to access controller from a route?

<a href="#" class="btn" {{action "someAction" user}}>add</a>

App.ApplicationRoute = Ember.Route.extend
  events:
    someAction: (user) ->
      console.log 'give me name from currentUser controller'

The someAction is very general and I think that ApplicationRoute is the best place for it.

I think the method controllerFor should be available in this event:

App.ApplicationRoute = Ember.Route.extend
  events:
    someAction: (user) ->
      console.log this.controllerFor("currentUser").get("name")

Update in response to the questions in the comments:

It all depends on what you want to do. Worrying about DRY on such a basic method, does not make much sense imho.

In your kudos left case I would do this:

App.ApplicationRoute = Ember.Route.extend
  events:
    someAction: (user) ->
      this.controllerFor("currentUser").decrementKudos();
      // implement the decrementKudos in your controller

But I guess storing this one controller should also work, if this is too much code for you:

App.ApplicationRoute = Ember.Route.extend
  currentUserCon : this.controllerFor("currentUser")
  events:
    someAction: (user) ->
      this.currentUserCon.decrementKudos();
      // implement the decrementKudos in your controller

In the newer version of ember you can access current route's controller in route as below

Ember version 2.5

currentUserCon : this.controller

if you want to access other routes controller then use controllerFor method.

this.controllerFor('path to controller'); //put path to controller as parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM