ember - 渲染模型hasMany属性

时间:2013-12-23 10:06:54

标签: ember.js ember-data handlebars.js

您好,感谢您花时间帮我解决问题。

我在使用把手渲染模型的属性时遇到困难。这是代码:

App.Project = DS.Model.extend({
    name: DS.attr('string'),
    teams: DS.hasMany('team', {async: true})
    // teamEffort: DS.attr('array')
});

App.Team = DS.Model.extend({
    name: DS.attr('string'),
    project: DS.belongsTo('project')
});

App.Team.FIXTURES = [
    {
        id: 1,
        name: 'Team 1',
        project: 1
    },
    {
        id: 2,
        name: 'Team 1',
        project: 2
    },
...]

App.Project.FIXTURES = [
    {
        id: 1,
        name: 'Project 1 - Test',
        teams: ['1', '3']      
    },
    {
        id: 2,
        name: 'Project 2 - Test',
        teams: ['2', '4', '5']
    }
...
];

并拥有以下html:

...
<script type="text/x-handlebars" data-template-name="projects">
        <!-- TODO: add css classes -->
        Test
        {{#each project in model}}
            {{#each team in project.teams}}
                aaaaaaa
            {{/each}}
        {{/each}}
        <table class="table table-bordered">
            <thead>
                <th colspan="4">Project Name</th>
            </thead>
            <tbody>
                {{#each project in model}}
                    <tr>
                        {{#each team in project.teams}}
                            aaaa
                        {{/each}}
                        <td colspan="4">{{project.name}}</td>
                    </tr>
                {{/each}}
            </tbody>
        </table>
    </script>
...

的application.js:

App = Ember.Application.create();

App.ApplicationAdapter = DS.FixtureAdapter;

App.Router.map(function(){
    this.resource('projects', {path: '/'});
});

router.js:

App.ProjectsRoute = Ember.Route.extend({
    model: function(){
        return this.store.find('project');
    }
});

使用Ember Chrome插件进行调试时,我可以看到项目相应地与2个和3个团队相关联,这是正确的,但是,当我运行{{log project.teams.length}}时,我总是得到0。怀疑它与我在上面的模型中添加属性async:true这一事实有关,但是没有它我的代码就不会运行。

project.name按预期打印出来。我无法获得对嵌套关系团队的引用。

我现在已经打了3个半小时。任何帮助将不胜感激!

非常感谢!

1 个答案:

答案 0 :(得分:1)

灯具适配器不会强制ID,确保您的ID类型匹配(也就是“1”!= 1)(其余适配器强制执行)。

http://emberjs.jsbin.com/OxIDiVU/78/edit