骨干中的比较器嵌套模型?

时间:2013-12-11 20:23:06

标签: backbone.js

如果我在骨干集合上使用比较器,我是否能够将具有相同属性的模型嵌套到div中?实例

// My dummy json
[{name: 'Robert', team: 'Redskins'},{name: 'Aaron', team: 'Packers'},{name: 'Kirk', team: 'Redskins'}]

然后这是我的收藏。

var Players = Backbone.Collection.extend({
    url: 'data/players.json',
    comparator : 'team'
});

我觉得这很酷,因为在我的渲染视图中,我看到模型按团队顺序列出,例如。

<div>
    <li>Robert</li>
    <li>Redskins</li>
</div>
<div>
    <li>Kirk</li>
    <li>Redskins</li>
</div>
<div>
    <li>Aaron</li>
    <li>Packers</li>
</div>

以下是我的观点代码。

var Player = Backbone.View.extend({
    el: '.app',
    render: function() {
        var self = this;
        var players = new Players();
        players.fetch({
            success: function(players) {
                var template = _.template($('#appTemplate').html(), {players: players.models});
                self.$el.html(template);
            }
        });
    }
});

现在谈到肉,最简单的方法是将球队分组到一个窝里,例如下面。

<div class="Redskins">
    <div>
        <li>Robert</li>
        <li>Redskins</li>
    </div>
    <div>
        <li>Kirk</li>
        <li>Redskins</li>
    </div>
</div>
<div class="Packers">
    <div>
        <li>Aaron</li>
        <li>Packers</li>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

如果不解析/操纵数据,我无法想到任何方法可以实现这一目标。您可以劫持toJSON()方法或完全添加新方法。例如:

var Players = Backbone.Collection.extend({
    url: 'data/players.json',
    comparator : 'team',
    toJSON: function() {
        var team,
            index = 0,
            grouped = [],
            raw = _.clone(this.attributes);

        _.each(raw, function(element) {
            var thisTeam = element.team;
            if (thisTeam != team) { // create new grouping
                grouped[index] = {
                    team: thisTeam,
                    players: []
                }
                grouped[index].players.push(element.name);
                index++;
            } else { // use existing grouping                
                grouped[index].players.push(element.name);
            }
        });

        return grouped;
    }
});

警告:这是未经测试的代码,仅供参考。无论如何,这段代码会给你一些JSON:

[
    {
        team: "Packers",
        players: ["Aaron"]
    },
    {
        team: "Redskins",
        players: ["Robert", "Kirk"]
    }
]

以下是Handlebars模板示例:

{{#each this}}
<div class="{{team}}">
    <div>
    {{#each players}}
        <li>{{this}}</li>
    {{/each}}
    </div>
</div>
{{/each}}