简体   繁体   English

如何从Ember的路线访问控制器?

[英]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. someAction非常通用,我认为ApplicationRoute是最好的选择。

I think the method controllerFor should be available in this event: 我认为方法controllerFor应该在这个事件中可用:

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. 在这样一个基本方法上担心DRY,没有多大意义。

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中,您可以在路径中访问当前路径的控制器,如下所示

Ember version 2.5 Ember版本2.5

currentUserCon : this.controller

if you want to access other routes controller then use controllerFor method. 如果要访问其他路由控制器,则使用controllerFor方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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