Binding child views and collections within an outl

2019-05-22 16:54发布

问题:

I'm trying to render a view Team inside of an {{outlet}}. This Team view is comprised of a simple Person view (the team leader), and a collection of Person views (team members). The outlet is set up by calling connectOutlet() on the ApplicationController.

Although the Person child views are rendered in the markup as expected, all the values of name are missing. It sure seems like my bindings and/or controller are not set up properly. What am I missing?

Code and demo: http://jsfiddle.net/aek38/fkKFJ/

The relevant handlebar templates are:

<script type="text/x-handlebars" data-template-name="app">
    <div class="container">
        {{outlet}}
    </div>
</script>

<script type="text/x-handlebars" data-template-name="person">
    <em>Person name is:</em> {{name}}
</script>

<script type="text/x-handlebars" data-template-name="team">
    <h3>Team Leader</h3>
    <em>Leader name should be:</em>{{leader.name}}
    {{view App.PersonView contentBinding="leader"}}
    <h3>Team Members</h3>
    {{#collection contentBinding="members"}}
        {{view App.PersonView contentBinding="content"}}
    {{/collection}}
</script>

Code snippet:

App = Ember.Application.create({
ready: function() {
    this.initialize();
},
ApplicationController: Ember.Controller.extend(),
ApplicationView: Ember.View.extend({
    templateName: "app"
}),

Person: Ember.Object.extend({
    name: "Jane Doe"
}),
PersonController: Ember.ObjectController.extend(),
PersonView: Ember.View.extend({
    templateName: "person"
}),

Team: Ember.Object.extend({
    members: [],
    leader: null
}),
TeamController: Ember.ObjectController.extend(),
TeamView: Ember.View.extend({
    templateName: "team"
}),
// ...

回答1:

You can use

{{view App.PersonView contextBinding="leader"}}

and use {{#each}} instead of {{#collection}} for the members

http://jsfiddle.net/LQTsV/1/



回答2:

Not very sure whats going on but I tweaked your fiddle to get it working:

http://jsfiddle.net/lifeinafolder/sPcwv/

Seems as if bindings are not working properly in the sense:

contentBinding="this"

works but

contentBinding="this.leader"

doesn't.

Sorry but I couldn't work it out more.



回答3:

You're setting the content variable on person view via contentBinding that should probably be personBinding. And then in your template you should get the view.person.name.

{{collection}} should be a {{each}} block.

{{#each members}}
    {{view App.PersonView personBinding="this"}}
{{/each}}

And this person template will look in the right location for the name.

<script type="text/x-handlebars" data-template-name="person">
    <em>Person name is:</em> {{view.person.name}}
</script>

Didn't change your js.

fiddle: http://jsfiddle.net/albertjan/fkKFJ/9/