【问题标题】:How can I set a link to route with a dynamic segment如何设置链接以使用动态段进行路由
【发布时间】:2013-04-30 22:08:12
【问题描述】:

如何设置链接以使用动态分段进行路由。根据指南,我从这个开始

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

在我的模板中:

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

不幸的是,这给了我以下错误:

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' 

【问题讨论】:

    标签: ember.js ember-router


    【解决方案1】:

    {{linkTo}} 需要Router.map 中定义的路由,因此根据您的映射,它应该只是product

    对于动态段,您还必须传递一个将在ProductRoute 中序列化的对象。由于 Ember 依赖于约定,因此几乎所有场景中的序列化都不需要开发人员做任何事情。在极少数情况下,必须实现 serializelittle differently,但在大多数情况下,您不必触摸它。

    如果您在{{each}} 循环中使用{{linkTo}},您可以这样做:

    {{#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 挂钩的参数。这就是你调用find 传递params.product_id 作为参数的地方。然后模型返回该模型的承诺,setupController 将使用该模型,将对象以controller.content 或简单地controller 暴露给视图层。

    【讨论】:

    • #each-loop 我不得不引用product:{{#linkTo 'product' this}}Details{{/linkTo}}
    猜你喜欢
    • 1970-01-01
    • 2013-02-28
    • 2020-10-11
    • 2022-11-25
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多