Michael Joseph Aubry
Michael Joseph Aubry

Reputation: 13412

Access an array of models?

Im a little stuck, I am using backbone.js the code below returns an array of models see image below.

//The array of objects
var teamPlayers = this.players.where({team_id: team.get('id')})

players is a collection. Instead of saying this.players.each(function(models){ //code here }) I want to say something like teamPlayers.each(function(models){ //code here }). So I can associate two collections matching their id's

enter image description here

I can do this successfully inside a template, but I need to separate my team views from my player views then render it in an app view.

Here is the template I am trying to achieve a result like this.

<script type="text/template" id="allTemplate">

    <% _.each(teams, function(team) { %>

            <div class="<%= team.name %>">

            <h1><%= team.name %></h1>

            <% var teamPlayers = _.where(players, {team_id: team.id}) %>

                <% _.each(teamPlayers, function(player) { %>
                    <li> <%= player.name %> </li>
                <% }); %>

            </div>

    <% }); %>


</script>

So I am trying to convert that template into javascript so that I can do a for each on the view.

Extra: here is what the each collection code looks like

this.teams.each(function(team) {
    var teamView = new TeamView({ model: team });
    var teamHtml = teamView.render().el;
    this.$el.append(teamHtml);

    var teamPlayers = this.players.where({team_id: team.get('id')})
    console.log(teamPlayers)

    this.players.each(function(player) {
        var playerView = new PlayerView({ model: player });

        var playerHtml = playerView.render().el;
        this.$el.append(playerHtml);
        console.log(player.toJSON());
    }, this);

}, this);

Edit: I just wanted to add I came across this Backbone.js Uncaught TypeError: Object [object Array] has no method 'on' it kind of makes sense but I cant figure out how to apply that answer to my project and the way I have created my pattern.

Upvotes: 0

Views: 50

Answers (1)

GijsjanB
GijsjanB

Reputation: 10044

_.where returns an array, not a Backbone.Collection, so turn:

this.players.each(function(player) {

into

_.each(teamPlayers, function(player) {

Upvotes: 1

Related Questions