结合两个集合backbone.js

时间:2013-11-27 06:12:26

标签: javascript jquery backbone.js

我正在制作一个篮球统计应用程序,有一系列球员及其属性。

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));
    }

});

在控制台内部我看到两个型号,但玩家是空的。

enter image description here

这不是一个大问题,我只是一个菜鸟,不知道如何接近:)

我想得到这样的结果。实际上这可能很难将球员加入球队,我怎么能说这些球员都在这支球队?

<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>

1 个答案:

答案 0 :(得分:2)

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