【问题标题】:Combining two collections backbone.js结合两个集合backbone.js
【发布时间】:2013-12-12 15:57:21
【问题描述】:

我正在制作一个篮球统计应用程序,其中包含球员及其属性的集合。

players = new App.Collections.PlayersList(
    [
        {   
            name: 'McGee',
            points: '14'
        },
        {
            name: 'Joe E',
            points: '21'
        },
        {
            name: 'Mike',
            points: '8'
        }
    ]
);

然后我有一个团队列表

teams = new App.Collections.TeamsList(
    [
        {   
            team: 'Green', //Accidentally used uppercase, will change that, just didnt want to confuse you because it's uppercase in the console.log picture below
        },
        {
            team: 'Blue',
        }
    ]
);

我关注了这个How to place a collection within a model in Backbone.js? 并添加到我的团队模型中。

App.Models.Team = Backbone.Model.extend({
    // Default attributes for the player item.
    initialize: function() {
        // assuming Players a collection of players
        console.log(this.set('players', new App.Collections.PlayersList));
    }

});

在控制台中,我看到两个模型,但玩家是空的。

这不是什么大而复杂的问题,我只是一个菜鸟,不知道如何处理:)

我试图得到这样的结果。其实这可能很难让一个球员加入一个球队,我怎么能说这些球员在这个球队呢?

<div class="green">
    <li data-player="McGee">Name: McGee, Points: 14</li>
    <li data-player="Joe">Name: Joe E, Points: 21</li>
    <li data-player="Mike">Name: Mike, Points: 8</li>
</div>

// Havent created players for this yet, but you get it
<div class="blue">
    <li class="">Name: McGee, Points: 14</li>
    <li class="">Name: Joe E, Points: 21</li>
    <li class="">Name: Mike, Points: 8</li>
</div>

编辑: 所以我正在尝试一些东西,这并不理想,但到目前为止它的工作,希望我能得到答案,我的意思是这是理想的还是我确信有一个更好的方法,我在这里学习。

window.greenTeam = new App.Collections.PlayersList(
    [
        {   
            team: 'green',
            name: 'McGee',
            points: '14'
        },
        {
            team: 'green',
            name: 'Joe E',
            points: '21'
        },
        {
            team: 'green',
            name: 'Mike',
            points: '8'
        }
    ]
);

window.blueTeam = new App.Collections.PlayersList(
    [
        {   
            team: 'blue',
            name: 'Steve',
            points: '14'
        },
        {
            team: 'blue',
            name: 'Eli',
            points: '21'
        },
        {
            team: 'blue',
            name: 'John',
            points: '8'
        }
    ]
);

window.orangeTeam = new App.Collections.PlayersList(
    [
        {   
            team: 'orange',
            name: 'Kobe',
            points: '14'
        },
        {
            team: 'orange',
            name: 'Lebron',
            points: '21'
        },
        {
            team: 'orange',
            name: 'Melo',
            points: '8'
        }
    ]
);


//Create new instaces to initialize each view

// New *App.Views.Player* instance, need to instantiate to set the model in the view.
// ------------
//window.playersView = new App.Views.Players({ collection: players });

window.greenTeamView = new App.Views.Players({ collection: greenTeam });
window.blueTeamView = new App.Views.Players({ collection: blueTeam });
window.orangeTeamView = new App.Views.Players({ collection: orangeTeam });

编辑:好的,这不是理想的哈哈,但它有效,看看我的完整代码,我知道我在这里扔了很多话但是,如果你看到这段代码,你会如何简化它,指点谁解决了这个难题:)

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

    <div class="green"></div>

    <div class="blue"></div>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="http://underscorejs.org/underscore.js"></script>
    <script src="http://backbonejs.org/backbone.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.1.0/backbone.localStorage-min.js"></script>

    <!-- Templates -->
    <script type="text/template" id="player-template">
        <div class="">Name: <%= name %> - Points: <%= points %><button class="btn"></button></div>
    </script>

<script>
$(function(){

    //Name spacing
    window.App = {
        Models: {},
        Collections: {},
        Views: {},
        Router: {}
    };


/*** OUR MODEL OF A PLAYER... PLAYER MODEL then SINGLE PLAYER VIEW ***/

    // Player Model
    // ----------

    // Our **Player** model has `name`, `points`, and `rebounds` attributes.
    window.App.Models.GreenPlayer = Backbone.Model.extend({
        // Default attributes for the player item.
        defaults: {
            team: "Green",
            name: "Michael",
            points: 10,
            rebounds: 9
        }

    });

    window.App.Models.BluePlayer = Backbone.Model.extend({
        // Default attributes for the player item.
        defaults: {
            team: "Blue",
            name: "Michael",
            points: 10,
            rebounds: 9
        }

    });

    // Single player view
    // ---------------

    // This is a view of how a player should look.
    window.App.Views.GreenPlayer = Backbone.View.extend({

        //el is a list tag.
        tagName:  "li",

        // Cache the template function for a single item.
        template: _.template($('#player-template').html()),

        events: {
            'click .btn': 'mikeAlert'
        },

        mikeAlert: function() {
           alert('get food');
        },

        // Re-render the titles of the todo item.
        render: function() {
          this.$el.html( this.template( this.model.toJSON() ) );
          this.$el.addClass( this.model.get('name') );
          var test = this.model.get('name');
          return this;
        }

    });

    // This is a view of how a player should look.
    window.App.Views.BluePlayer = Backbone.View.extend({

        //el is a list tag.
        tagName:  "li",

        // Cache the template function for a single item.
        template: _.template($('#player-template').html()),

        events: {
            'click .btn': 'mikeAlert'
        },

        mikeAlert: function() {
           alert('get food');
        },

        // Re-render the titles of the todo item.
        render: function() {
          this.$el.html( this.template( this.model.toJSON() ) );
          this.$el.addClass( this.model.get('name') );
          var test = this.model.get('name');
          return this;
        }

    });


/*** END PLAYER MODEL SETUP ***/



/*** OUR PLAYERS COLLECTION... PLAYERS COLLECTION then PLAYERS COLLECTION VIEW ***/

    // Players Collection
    // ---------------

    // We connect the players collection to the player model
    // The collection of players is backed by *localStorage* instead of a remote
    // server.
    window.App.Collections.GreenPlayersList = Backbone.Collection.extend({

        // Reference to this collection's model.
        model: App.Models.GreenPlayer

        // Save all of the player items under the `"players-backbone"` namespace.
        //localStorage: new Backbone.LocalStorage("players-backbone"),

    });

    window.App.Collections.BluePlayersList = Backbone.Collection.extend({

        // Reference to this collection's model.
        model: App.Models.BluePlayer

        // Save all of the player items under the `"players-backbone"` namespace.
        //localStorage: new Backbone.LocalStorage("players-backbone"),

    });


    // Players Collection View
    // ---------------

    // Display a list of all player*s* here.
    window.App.Views.GreenPlayers = Backbone.View.extend({
        // Instead of generating a new element, bind to the existing skeleton of
        // the App already present in the HTML.
        el: $(".app"),

        initialize: function() {
            this.render();
        },

        render: function() {
            this.collection.each(this.addOne, this);
            return this;
        },

        addOne: function(model) {

            //Create a new child view
            var greenplayer = new App.Views.GreenPlayer({ model: model });
            $('.green').append( greenplayer.render().el );

        }

    });

    window.App.Views.BluePlayers = Backbone.View.extend({
        // Instead of generating a new element, bind to the existing skeleton of
        // the App already present in the HTML.
        el: $(".app"),

        initialize: function() {
            this.render();
        },

        render: function() {
            this.collection.each(this.addOne, this);
            return this;
        },

        addOne: function(model) {

            //Create a new child view
            var blueplayer = new App.Views.BluePlayer({ model: model });
            $('.blue').append( blueplayer.render().el );

        }

    });


/*** END PLAYER*S* COLLECTION SETUP ***/


    // Dummy Collection, new instance of *App.Collections.PlayersList* 
    // ---------------
    window.greenTeam = new App.Collections.GreenPlayersList(
        [
            {   
                team: 'green',
                name: 'McGee',
                points: '14'
            },
            {
                team: 'green',
                name: 'Joe E',
                points: '21'
            },
            {
                team: 'green',
                name: 'Mike',
                points: '8'
            }
        ]
    );

    window.blueTeam = new App.Collections.BluePlayersList(
        [
            {   
                team: 'blue',
                name: 'Steve',
                points: '14'
            },
            {
                team: 'blue',
                name: 'Eli',
                points: '21'
            },
            {
                team: 'blue',
                name: 'John',
                points: '8'
            }
        ]
    );


    //Create new instaces to initialize each view

    // New *App.Views.Player* instance, need to instantiate to set the model in the view.
    // ------------
    //window.playersView = new App.Views.Players({ collection: players });

    window.greenTeamView = new App.Views.GreenPlayers({ collection: greenTeam });
    window.blueTeamView = new App.Views.BluePlayers({ collection: blueTeam });
    //window.orangeTeamView = new App.Views.Players({ collection: orangeTeam });


});
</script>

</body>
</html>

【问题讨论】:

  • 这有意义吗?如果有其他方法 id 想听..
  • 这对任何人都有意义吗,我只是想将一个球员与一个球队联系起来,但我需要将球员列表包装在球队视图中。最终结果应该看起来像 HTML上面的帖子。

标签: javascript jquery backbone.js


【解决方案1】:

在您的情况下,可以有很多支球队(绿色、蓝色等),每支球队可以有很多球员。一种方法是拥有两个不同的模型TeamPlayer,然后与Team -&gt; Player 建立one-to-many 关系。最后创建一个CollectionTeam。查看Backbone Associations 管理关系。希望这会有所帮助。

【讨论】:

  • 好的,我会看看谢谢,我真的在 3 天前拿起了骨干,我在 OOP 方面是个新手,所以实例化和所有这些东西都是新的,但我坚持在那里,我希望这个很清楚,可以帮助组织我的代码:) 到目前为止,一对多的关系听起来很酷,我希望我可以将它应用到我的项目中。
  • 我确实遇到了这个问题,因为我需要 1+ 来发布这个,因为我需要站起来继续学习如何使用它。起初看起来工作量很大,但病态的人大声笑。
  • 无论如何你可以提供一个粗略的简单例子,我给你点,我只是没有完全得到100%的文档......
猜你喜欢
  • 2012-05-10
  • 2012-10-30
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-19
相关资源
最近更新 更多