2013-04-30 54 views
6

如何設置鏈接以使用動態網段進行路由。根據指導我開始與這個如何設置鏈接以便與動態網段路由

window.App = Ember.Application.create() 
App.Router.map -> 
    @resource 'products' 
    @resource 'product', path: '/product/:product_id' 
在我的模板

{{#linkTo "product.1"}}products{{/linkTo}} 

很不幸,這給了我follwing錯誤:

Uncaught Error: assertion failed: The attempt to linkTo route 'product.1' failed. 
The router did not find 'product.1' in its possible routes: 'products', 'product', 'index' 

回答

10

{{linkTo}}預計在Router.map定義的路線,所以根據你的映射,它應該是簡單的product

至於動態段,你還必須傳遞一個對象,它將在ProductRoute中被序列化。幾乎所有情況下的序列化都是在沒有開發人員做任何事情的情況下進行的,因爲Ember依賴於約定。在極少數情況下,您必須執行serialize a little differently,但在大多數情況下您不必觸碰它。

如果您使用{{linkTo}}{{each}}循環中,你可以做這樣的:

{{#each product in controller}} 
    {{#linkTo product product}}Details{{/linkTo}} 
{{/each}} 

{{#each controller}} 
    {{#linkTo product this}}Details{{/linkTo}} 
{{/each}} 

其中第一個參數是路由名,第二個是你的模型目的。在第一個代碼中,該對象也被命名爲product,而在第二個代碼中,它僅僅被作爲this傳遞,這是迭代的結果。

如果有,你必須鏈接到一個動態路由,同時不使用所述{{each}}環路一個不尋常的情況下,你必須暴露在controller(優選的)對象或view。然後,你必須做類似下面的內容:

App.SomeController = Em.Controller.extend 
    product: null 

App.SomeRoute = Em.Route.extend 
    ### 
    controller is actually `SomeController` here 
    model is not being used, and is null, while the actual model being 
    supplied to the controller is `product`, retrieved from store 
    ### 
    setupController: (controller, model) -> 
    product = App.Product.find 1 
    controller.set 'product', product 
    return 

當你的模板將與此類似:

{{#linkTo product controller.product}}Product{{/linkTo}} 

怎樣的路線知道ID?

Conventions。路線將serialize您傳遞的對象,並暴露一個單一的屬性,具有該路線模型的名稱的對象,其次是「_id」,在這種情況下,這將是product_id,所以當您單擊該鏈接時,該應用程序激活ProductRoute,運行序列化方法創建該id屬性,該屬性隨後將用作model掛鉤的參數。這就是你通過params.product_id作爲參數呼叫find的地方。然後該模型返回該模型的承諾,該模型將由setupController使用,將對象展示爲視圖層controller.content或簡單地controller

+0

在'#each'-loop中,我必須引用'product':'{{#linkTo'product'this}} Details {{/ linkTo}}'。 – 2013-11-07 14:23:38