javascript 如何从 Ember 的路由访问控制器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15911704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access controller from route in Ember?
提问by wryrych
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 是它的最佳位置。
回答by mavilein
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")
Updatein 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
回答by murli2308
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.