Skip to content Skip to sidebar Skip to footer

Backbone.js Adding Model To Collection Adds To All Models In Collection

Playing around with backbone.js, so far I've created models and collections for a deck of cards and two players. The problem is when I try move a card from the deck and add it to t

Solution 1:

Objects defined in a model's defaults hash end shared between instances (see In what cases does defaults need to be a function? for a longer explanation)

Use a function to return your defaults values :

game.Player = Backbone.Model.extend({
    defaults: function() {
        return {
            name : "",
            hand : new game.Hand()
        };
    }
});

and a demo

var game = {};

game.Card = Backbone.Model.extend({
    defaults: {
        "suit" : "spades",
        "rank" : "A"
    }
});
game.Hand = Backbone.Collection.extend({
  model : game.Card
});

game.Player = Backbone.Model.extend({
    defaults: function() {
    return {
        hand: new game.Hand()
    };
  }
});
var players = newBackbone.Collection([
    new game.Player (),
    new game.Player ()
]);


var deck = newBackbone.Collection([
    {suit: "heart", rank: "A"}, {suit: "heart", rank: "2"}
]);
//the first card goes to player1var topCard = deck.at(0); //A of hearts
deck.remove(topCard);
var hand1 = players.at(0).get("hand");
hand1.add(topCard);

//the second card goes to player2
topCard = deck.at(0); //2 of hearts
deck.remove(topCard);
var hand2 = players.at(1).get("hand");
hand2.add(topCard);

$('body').append("Hand 1 " + JSON.stringify(hand1.toJSON()));
$('body').append("Hand 2 " + JSON.stringify(hand2.toJSON()));
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js"></script>

Post a Comment for "Backbone.js Adding Model To Collection Adds To All Models In Collection"