[英]How do I disambiguate nested routes in ember.js?
我有兩個資源都具有相同的子資源:
App.Router.map(function() {
this.resource('post', function() {
this.resource('comments', function() {
this.route('new');
});
});
this.resource('product', function() {
this.resource('comments', function() {
this.route('new');
});
});
});
問題是,ember路由器只根據當前和父路由構建路由對象的名稱,而不是整個層次結構。 因此,它嘗試將/posts/:id/comments/new
和/products/:id/comments/new
App.NewCommentRoute
到App.NewCommentRoute
對象。 我該怎么做才能解決這個問題?
這篇文章改編自GitHub問題 。
我把James A. Rosen的解決方案更進了一步,它就像一個魅力。 有點多余,但讓事情更加直觀:
App.Router.map(function() {
this.resource('post', function() {
this.resource('post.comments', { path: '/comments' }, function() {
this.route('new');
});
});
this.resource('product', function() {
this.resource('product.comments', { path: '/comments' }, function() {
this.route('new');
});
});
});
現在,您可以像原先預期的那樣使用transitionTo('product.comments.new')
或App.register('route:product.comments.new', myRouteHandler)
。
如果您沒有手動注冊路由處理程序,Ember會優雅地在App.ProductCommentsNewRoute
查找它
唯一的缺點是使用與父資源已有的相同的根名稱來定義子資源名稱的冗余。
指定路徑時,路徑默認為路徑名稱,但您可以覆蓋該行為。 您可以通過向名稱添加更多信息來消除深層嵌套路由的歧義。 有兩種方法可以實現基本相同的結果:
App.Router.map(function() {
this.resource('post', function() {
this.resource('postComments', { path: '/comments' }, function() {
this.route('new');
});
});
this.resource('product', function() {
this.resource('productComments', { path: '/comments' }, function() {
this.route('new');
});
});
});
App.Router.map(function() {
this.resource('post', function() {
this.resource('comments', function() {
this.route('newPost', { path: '/new' });
});
});
this.resource('product', function() {
this.resource('comments', function() {
this.route('newPost', { path: '/new' });
});
});
});
在這兩種情況下,路由器現在都將查找App.NewPostCommentsPath
和App.NewProductCommentsPath
。 第一個優點是第二個優點是,如果你想在外部引用路由,它們看起來像“postComments.new”而不是“comments.newPost”。 前者對我說得更好。
兩年過去了,Ember已經有了很大的進步。
自Ember 1.7起,路線也可以有子路線: http ://emberjs.com/blog/2014/08/23/ember-1-7-0-released.html#toc_new-features。
所以我們可以將其重寫為:
this.route('post', function() {
this.route('comments', { path: '/comments' }, function() {
this.route('new');
});
});
this.route('product', function() {
this.route('comments', { path: '/comments' }, function() {
this.route('new');
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.