I would like to know what the difference is (if any) between the following:
-
{{#each}}
using{{this}}
-
{{#each item in model}}
using{{item}}
-
{{#each item in controller}}
using{{item}}
-
{{#each item in controller.model}}
using{{item}}
I would like to know what the difference is (if any) between the following:
{{#each}}
using {{this}}
{{#each item in model}}
using {{item}}
{{#each item in controller}}
using {{item}}
{{#each item in controller.model}}
using {{item}}
The concept is difficult to grasp at first, luckily Ember 2.0 will simplify the usage a lot. The main thing to understand is that an ArrayController proxies requests to the model (if a property is not found on the controller, it tries to access it on the model instead). A handlebars each loop is directly proxied to the model.
This means that {{#each item in controller}}
translates to {{#each item in model}}
, which is also the same as {{#each item in controller.model}}
.
The {{#each}}
helper without arguments loops over what’s currently {{this}}
, which is the controller (proxied to the model) property in a controller template. It then switches context so that {{this}}
inside of the loop is the current object in the iteration. This method will soon become deprecated, as it is just too complicated.
The best, most future proof way of doing it today is {{#each item in model}}
. I even like to set up an alias in my controller like so:
todos: Ember.computed.alias('model')
so that I can write
{{#each todo in todos}}
in my templates.
Great explanation, thanks! I especially like the idea of including a computed alias in the controller, is this something that will be included automatically in Ember 2.0?
I think the model hook in routes will be replaced or extended with an attrs
hook, where you can pass any number of arguments to the controller (or rather, component as of 2.0).
attrs: function() {
return {
todos: this.store.find('todo'),
someOtherNamedThing: ...
};
}
This also means that you could easily have multiple different models per controller, all asynchronously loaded for you. Pretty sweet!
Now that would be a really great improvement, fingers crossed.