John P.
John P.

Reputation: 43

{{#each objects}} vs. {{#each model.objects}} vs. {{#each content.objects}}

I wrote a very simple route that exports an object with a sub-collection as its model:

App.IndexRoute = Ember.Route.extend({
    model: function() {
        return Ember.Object.create({
            objects: [...]
        });
    }
});

Now in my template I try iterating over the objects like so:

{{#each objects}}
    ...
{{/each}}

For some reason this works in the official ember jsfiddle, but when I run the same code locally, I have to change it to {{#each content.objects}} to make it work. The only differences I spot between my case and the jsfiddle are:

  1. I use browserify + hbsify to compile the template, and am not using inline handlebars templates
  2. I don't define an application template, while the jsfiddle does.

What am I missing?

Upvotes: 2

Views: 75

Answers (1)

GJK
GJK

Reputation: 37369

I can explain the differences between the 3, and hopefully that will clear things up a bit.

  • {{#each objects}} - This pulls from the objects property on the controller. If you've explicitly defined a property named objects, it will use that. But if you haven't explicitly defined one, which I assume is the case, the controller (which extends from ObjectProxy), will proxy the request to the content property.

    So first Ember calls controller.get('objects'), which will return undefined since you didn't define an objects property. From there, the unknownProperty function will be called, which will return the content of content.objects instead.

    Bottom line, using this form will differ depending on how your controller is declared. Try to avoid this one if possible.

  • {{#each model.objects}} - model is actually an alias for content but you're not technically supposed to know that. The content property is merely an implementation detail of how Ember object proxies work.

    In the end, just know that model holds your current model, and you should prefer this method of accessing properties. (Because in my opinion, it eliminates ambiguity.)

  • {{#each content.objects}} - content is an implementation detail of Ember's object proxies. In this particular case, content is the model that you supplied. You should avoid using this method, as it relies on the property of the object proxy to be named content (which could technically change at any time).

So for your problem, I imagine that {{#each objects}} isn't working because there is another objects property defined somehow. You should use {{#each model.objects}} instead. (Or, if you can, switch to an ArrayController and just use {{#each}}.

Upvotes: 1

Related Questions