0

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.

1 Answer 1

1

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

this.players.each(function(player) {

into

_.each(teamPlayers, function(player) {
Sign up to request clarification or add additional context in comments.

1 Comment

Oh wow, thanks dude! I adopted this.players.each from a tutorial. This worked, it's amazing how one little thing can throw all of your application off.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.