在EmberJS中获取父路由 [英] Getting parent route in EmberJS
问题描述
我目前正在使用 transitionToRoute('blog_post')
,但从长远来看这不行因为我希望这个代码一般运行任何模型(即它不会知道路由的名称,所以我不能调用'blog_post')。我想我正在寻找类似Rails的 url_for
或一种说法 router.get('parent_route')
(或 controller.get('parent_route')
)。
任何指针或想法?谢谢。
这是在2013年为了ember v0.9.8或某事而回答的,框架已经来了从那以后的很长的路。我认为当前版本的框架可能会有更好的解决方案。既然,我没有与Ember联系,不能真正更新这个答案!
从源代码中的私有函数启发,添加以下方法返回 parentRoute
Ember的路由.Route.reopen({
getParentRoute:function(){
var route = this;
var handlerInfos = route.router.router.currentHandlerInfos;
var parent,current;
for(var i = 0,l = handlerInfos.length; i< l; i ++){
current = handlerInfos [i] .handler;
if((current.routeName == route.routeName)||(current.routeName.match(/./)&& current.routeName.split('。')[1] == route.routeName)){
return parent .routeName;
}
parent = current;
}
}
})
使用里面的路线如下
App.SomeRoute = Ember.Route.extend {
events:{
goBack:function (){
this.transitionTo(this.getParentRoute());
}
}
})
Handlebars
< script type =text / x-handlebarsdata-template-name =some>
< a href =#{{action goBack}}>返回< / a>
< / script>
对于实际代码,打开这个,并执行一个CTRL + F为 function parentRoute
I'm making a reusable (sort of polymorphic) comments widget. I want a button that enables me to go back to the parent route (e.g., if I'm at /blog_posts/1/comments, I want the button to take me back to /blog_posts/1).
I'm currently using transitionToRoute('blog_post')
, but this won't work in the long run because I want this code to generically run with any model (i.e. it won't know anything about the route's name, so I can't call 'blog_post'). I guess I'm looking for either something like Rails' url_for
, or a way of saying router.get('parent_route')
(or controller.get('parent_route')
).
Any pointers or ideas? Thanks.
This was answered in the year 2013 for ember v0.9.8 or something, the framework has come a long way since then. I think there might be a much better solution with the current version of the framework. Since, I'm not in touch with Ember, can't really update this answer!
Inspired from a private function in the source code, Add the following method to the Routes which returns the name of the parentRoute
Ember.Route.reopen({
getParentRoute: function(){
var route = this;
var handlerInfos = route.router.router.currentHandlerInfos;
var parent, current;
for (var i=0, l=handlerInfos.length; i<l; i++) {
current = handlerInfos[i].handler;
if((current.routeName == route.routeName)||(current.routeName.match(/./) && current.routeName.split('.')[1] == route.routeName )){
return parent.routeName;
}
parent = current;
}
}
})
Use inside routes as follows
App.SomeRoute = Ember.Route.extend({
events: {
goBack: function(){
this.transitionTo(this.getParentRoute());
}
}
})
Handlebars
<script type="text/x-handlebars" data-template-name="some">
<a href="#" {{action goBack}}>Back</a>
</script>
For the actual code, open this and do a CTRL+F for function parentRoute
这篇关于在EmberJS中获取父路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!