2013-02-17 33 views
6

我有兩個資源都具有相同的子資源:如何在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'); 
    }); 
    }); 
}); 

的問題是,餘燼路由器構建的路徑對象的名稱出來只是當前和家長的路線,而不是出於整體的層次結構。因此,它試圖將/posts/:id/comments/new/products/:id/comments/new路由到App.NewCommentRoute對象。我能做些什麼來解決這個問題?

此帖被改編自GitHub issue

+0

這原本是我的問題:https://github.com/emberjs/ember.js/issues/2086感覺有點像我的代表被挖走。 – KOGI 2013-02-17 19:44:36

+0

對不起。我沒有看到它。我會將我的答案標記爲社區wiki。 (問題不能,儘管我在問題文本中鏈接到了您的GitHub問題。) – 2013-02-17 20:19:33

+0

謝謝。不過,你的答案是你的,所以你應該得到所有的代表。只有原來的問題是我的。 – KOGI 2013-02-17 20:35:00

回答

6

我把詹姆斯·羅森的解決方案更進了一步,它像一個魅力一樣工作。有些多餘,但使事情更直觀的道路:

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)就像原先預期。

如果不手動註冊您的路由處理,灰燼,優雅,甚至會尋找它在App.ProductCommentsNewRoute

唯一的缺點是同根的名字確定該子資源的名稱的冗餘父資源已經擁有。

4

當您指定路線時,路徑默認爲路線的名稱,但您可以覆蓋該行爲。通過向名稱添加更多信息,可以消除深層嵌套路線的歧義。有兩種方法基本上實現相同的效果:

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.NewPostCommentsPathApp.NewProductCommentsPath。第一個優點是,如果你想從外部引用路由,它們看起來像「postComments.new」而不是「comments.newPost」。前者對我更好。

+0

+1感謝您的支持。這是一個有效的解決方法。雖然,正如GitHub上的原始線程中提到的那樣,Ember團隊應該滿意的並不是一個合適的解決方案。 – KOGI 2013-02-17 19:45:52

1

隨着兩年過去了,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'); 
    }); 
});