骨干集合不是唯一的? [英] Backbone Collection not unique?
问题描述
我有一个简单的设置去为一个应用程序在Backbone.js的结果的开始
在code在这一主旨。结果
这是pretty简单。 A 硬币
模型和收集,一个播放器
模型和收藏。每个玩家都有硬币的集合。我手动添加硬币的球员应该得到的类型。
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.
在年底初始化
,每个玩家的金币
收藏有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.
我是什么失踪?
推荐答案
我猜你的问题是在播放器你的
默认
code>:
I'd guess that your problem is your defaults
in Player
:
var Player = Backbone.Model.extend({
defaults: {
id: 0,
name: '',
coins: new Coins()
},
//...
});
这是默认
将浅拷贝到新的播放器
如此,他们都会最终完全共享同样硬币:新币()
。类似的事情发生,只要默认
包含任何可变数据(即数组,对象文本,...)。因此,所有这些:
That defaults
will be shallow-copied to new Player
s 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")
将最终成为完全相同的对象。该精细的手工有这样一段话:
默认 model.defaults或model.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.
请注意在最后那个小小的警告。如果您使用默认
功能:
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()
};
},
//...
});
那么你应该得到不同的'硬币'
每个播放器
。或者,您可以手动设置'硬币'
在初始化
:
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...
},
//...
});
这篇关于骨干集合不是唯一的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!