Skip to content

Instantly share code, notes, and snippets.

@johanvalcoog
Forked from sgharms/gist:2896428
Created June 9, 2012 05:59
Show Gist options
  • Save johanvalcoog/2899699 to your computer and use it in GitHub Desktop.
Save johanvalcoog/2899699 to your computer and use it in GitHub Desktop.
Ember 0.9.8 and VIEW_PRESERVES_CONTEXT
The first time I dropped 0.9.8 in, I was immediately struck with the
thought: "HOLY ZEBULON PIKE ON A ZEBRA, NONE OF THE ITEMS IN Ember.CollectionViews
ARE SHOWING?!"
The change has to do with whether views render their templates using
themselves as the context, or whether it is inherited from the parent.
Alternatively said:
"it is trying to look up [...] properties on the view instead of the
parent context[TD]."
Consider a folder list.
In `app_nav.hbars` we had:
{{view entriesBinding="App.folders.content" templateName="root-entries"}}
Therefore in `root-entries.hbars` you would expect that `{{#each
entries}}` (i.e. a proxy to App.folders.content) would get you
some sort of enumerable.
THIS DOES NOT WORK IN 0.9.8. <===========
What was happening is that the context in which that handlebars was
being interpreted was the VIEW **NOT** the parent OBJECT CONTEXT.
Therefore, to access `entries`
You need to refer to it as {{#each view.entries}}. <===========
Let's dig a little deeper.
<script type="text/x-handlebars" data-template-name="root-entries">
{{#each view.entries}}
{{view App.PrettyFolderView}}
{{/each}}
</script>
This is a more interesting case that shows the difference between the
context and the view.
It was:
{{view App.PrettyFolderView contentBinding="this"}}
Now it is:
{{view App.PrettyFolderView}}
You might be thinking: "Steven, you bozo, you've screwed up, there's
no way that the PrettyFolderView is going to know about that 'entry'
(or 'this') you have inside of your {{#each}} block." But here's the Ember 0.9.8 magic.
The context (i.e. the "this" is
*preserved* into the child view. {{#each}} and {{#with}} shift the
context so *even in FolderSelectorView* your context is no different
than it was in the {{#each}} block. As such you don't need to pass a
contentBinding.
As a benefit, the sub-view actually gets prettier!
- <h1 {{action "selectFolder"}}>{{content.label}}</h1>
+ <h1 {{action "selectFolder"}}>{{label}}</h1>
Resources:
[TD]: Tom Dale re: VPC: https://gist.github.com/2494968
[VG]: View Guide: http://emberjs.com/guides/view_layer
[SO]: http://stackoverflow.com/questions/10710963/in-ember-js-what-is-the-context-of-a-view-when-env-view-preserves-context-is-en
[JS]: http://jsfiddle.net/sgharms/PpYj9/4/ (JSFiddle that has these
environment variables set for testing that demonstrates the broken;
add "view." in two places to get it working -- test yourself! )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment