Tikhon Belousko
Tikhon Belousko

Reputation: 777

Issue with EmberJS link-to helper

I'm working on a simple restaurant menu and I have a code like this which works fine:

  <script type="text/x-handlebars" data-template-name="application">
      <h1> Categories </h1>
      {{#each}}
        {{#link-to "dish" this.id}} {{name}} {{/link-to}} 
        </br>
      {{/each}}
      {{outlet}}
  </script>

It works, but I still can't figure out why I should pass this.id to the parameter of a link-to. Inititaly I've passed just this to the helper and it didn't work (WHY?) and only after some time of debugging I made it work with this.id.

So the question is, why it works with this.id and doesn't work with this? All examples I've seen so far always used this so is it a good approach to use this.id? Please explain!

Here is the full code http://jsbin.com/AcoHeNA/44/

Upvotes: 1

Views: 66

Answers (1)

hso
hso

Reputation: 641

It works with this.id because the {{link-to}} helper can take:

  • The name of a route. In this case it would be "dish".
  • At most one model for each dynamic segment.
  • An optional title which will be bound to the a title attribute.

When you pass a model to the route, it doesn't fetch model data from a remote server, it takes "as is" and passes it to the controller.

If you pass an id to the helper, it makes sure to run the route's model hook with the id as an argument, retrieving the model's data.

What happens is that in your code you were passing this which is a Category model. The DishRoute is for Dish models so it just doesn't work.

It works if you pass this.id because it is an integer and Ember will fetch a Dish that happens to have the same id that whatever Category instance this is set to.

In doubt, read the official docs (http://emberjs.com/guides/templates/links/)

Upvotes: 1

Related Questions