Backbone Collection 不是唯一的吗? [英] Backbone Collection not unique?

查看:12
本文介绍了Backbone Collection 不是唯一的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的设置,用于在 Backbone.js 中启动一个应用程序
代码在本要点中.
这很简单.一个 Coin 模型和集合,一个 Player 模型和集合.每个玩家都有一个硬币的集合.我手动添加玩家应该获得的硬币类型.

I've got a simple setup going for the beginnings of an app in Backbone.js
The code is in this gist.
It is pretty straightforward. A Coin model and collection, a Player model and collection. Each Player has a collection of Coins. I manually add the type of Coins a player should be getting.

initialize结束时,每个玩家Coins集合中有32个项目,Coins.player_id设置为4个所有 4 名球员.

At the end of initialize, each of the Players Coins collection has 32 items in it and Coins.player_id is set to 4 in all 4 Players.

我错过了什么?

推荐答案

我猜你的问题是你在Player中的defaults:

I'd guess that your problem is your defaults in Player:

var Player = Backbone.Model.extend({
    defaults: {
        id: 0,
        name: '',
        coins: new Coins()
    },
    //...
});

那个 defaults 将被浅复制到新的 Player,所以他们最终都会共享完全相同的 coins: new Coins().每当 defaults 包含任何可变数据(即数组、对象文字等)时,都会发生类似的事情.所以所有这些:

That defaults will be shallow-copied to new Players so they'll all end up sharing exactly the same coins: new Coins(). Similar things happen whenever defaults contains any mutable data (i.e. arrays, object literals, ...). So all of these:

this.Taylor.get("coins")
this.Sugar.get("coins")
this.Darlene.get("coins")
this.Cody.get("coins")

最终将成为完全相同的对象.精美手册有这样的说法:

will end up as the exact same object. The fine manual has this to say:

defaults model.defaults 或 model.defaults()

defaults 哈希(或函数)可用于指定模型的默认属性.创建模型的实例时,任何未指定的属性都将设置为其默认值.
[...]
请记住,在 JavaScript 中,对象是通过引用传递的,因此如果您包含一个对象作为默认值,它将在所有实例之间共享.

The defaults hash (or function) can be used to specify the default attributes for your model. When creating an instance of the model, any unspecified attributes will be set to their default value.
[...]
Remember that in JavaScript, objects are passed by reference, so if you include an object as a default value, it will be shared among all instances.

请注意最后的小警告.如果您使用 defaults 的函数:

Note that little caveat at the end. If you use a function for defaults:

var Player = Backbone.Model.extend({
    defaults: function() {
        return {
            id: 0,
            name: '',
            coins: new Coins()
        };
    },
    //...
});

那么你应该为每个Player获得不同的'coins'.或者,您可以在 initialize 中手动设置 'coins':

then you should get distinct 'coins' for each Player. Alternatively, you could manually set 'coins' in your initialize:

var Player = Backbone.Model.extend({
    //...
    initialize: function() {
        this.set('coins', new Coins);
        // Or only set it if it isn't there if that makes sense...
    },
    //...
});

这篇关于Backbone Collection 不是唯一的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆