How to set a link to a route with a dynamic segment

How to set a link to a route with a dynamic segment. According to the manual, I start with this

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

in my template:

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

Unfortunately, this gives me the following error:

 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' 
+6
source share
1 answer

{{linkTo}} expects a route defined in Router.map , so according to your mapping it should just be a product .

As for the dynamic segment, you also need to pass the object to be serialized in ProductRoute . Serialization in almost all scenarios occurs without the involvement of the developer, as Ember relies on agreements. In rare cases, you need to serialize a slightly differently , but in most cases you do not need to touch it.

If you use {{linkTo}} inside the loop {{each}} , you can do it like this:

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

or

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

Where the first argument is the name of the route and the second is your model object. In the first code, the object was also named product , and in the second, it is simply passed as this , which is the iteration product.

If you have an unusual scenario where you must reference a dynamic route without using the {{each}} loop, you need to expose the object in the controller (preferred) or view . Then you will need to do something similar to the following:

 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 

So far, your template will look like this:

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

How does the route know the identifier?

Conventions . The serialize route of the object you are passing in and exposes an object with a single property that has a model name for this route, then follows "_id", which in this case will be product_id , so when you click this link, the application activates ProductRoute , launches the serialize method, creating this is the id property, which will later be used as the model argument. That you call find , passing params.product_id as an argument. Then the model returns the promise of this model, which will be used by setupController , displaying the object at the presentation level as controller.content or just controller .

+10
source

Source: https://habr.com/ru/post/943998/


All Articles