0

I am making a statistical app for basketball, there is a collection of players and their attributes.

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

Then I have a list of teams

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',
        }
    ]
);

I followed this How to place a collection within a model in Backbone.js? and added into my teams model.

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

});

Inside the console I see both models, but players is empty.

enter image description here

This is not some big complex issue, I am just a noob and have no idea how to approach :)

I am trying to get a result like this. Actually this may be tough attaching a player to a team, how would I say these players are on this team?

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

EDIT: So I am trying something out, this isnt ideal but so far its working, hopefully I can get an answer, I mean is this ideal or I am sure there is a better way to do this, I am here to learn.

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

Edit: Okay this is NOT ideal lol but it works, take a look at my full code, I know I am throwing out a lot of words here but, if you saw this code how would you simplify it, points to whomever solves this puzzle :)

<!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>
Community
  • 1
  • 1
Michael Joseph Aubry
  • 12,282
  • 16
  • 70
  • 135

1 Answers1

2

In your case there can be many teams (green, blue, etc) each team can have many players. One approach would be to have two different models Team and Player and then have one-to-many relationship from Team -> Player. Finally create a Collection of Team. Have a look at Backbone Associations for managing relationships. Hope this helps.

Niranjan Borawake
  • 1,628
  • 13
  • 20
  • Okay I will take a look thanks, I literally picked up backbone 3 days ago and I am a noobie in OOP, so instantiating and all that stuff is new, but I am hanging in there I hope this makes clear sense and can help organize my code :) So far one-to-many relationships sounds cool, I hope I can apply it to my project. – Michael Joseph Aubry Nov 27 '13 at 08:34
  • I did come across this before I had to 1+ you for posting this because I need to man up and just go ahead and learn how to use this. It looked like a lot of work at first, but ill man up lol. – Michael Joseph Aubry Nov 27 '13 at 08:44
  • Is there anyway you can provide a rough simple example, Ill give you points, I just don't quite get the documentation 100%... – Michael Joseph Aubry Nov 28 '13 at 04:10