I\'m running into an isssue when I try to create a collection of collections using backbone js. Here is the code :
Models and Collections :
var Track
I think your problem is your default tracks
attribute in PlayList
:
var Playlist = Backbone.Model.extend({
defaults : {
name : "",
tracks : new TrackCollection,
}
});
Backbone will shallow-copy the defaults when creating new instances:
defaults
model.defaults or model.defaults()
[...]
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.
The result is that every single PlayList
instance that uses the default tracks
will be using exactly the same TrackCollection
as its tracks
attribute and that TrackCollection
will be the one referenced in the defaults
.
The easiest solution is to use a function for defaults
:
var Playlist = Backbone.Model.extend({
defaults : function() {
return {
name : "",
tracks : new TrackCollection,
};
}
});
That way the defaults
function will be called when defaults are needed and each time defaults
is called you'll get a brand new TrackCollection
in the default tracks
attribute.
Here's a quick rule of thumb for you:
If you want to put anything other than strings, numbers, or booleans in
defaults
, use adefaults
function instead of adefaults
object.