当我尝试使用主干 js 创建集合集合时遇到了问题。这是代码:
模型和集合:
var Track = Backbone.Model.extend({
defaults : {
title : ""
}
})
var TrackCollection = Backbone.Collection.extend({
model : Track,
})
var Playlist = Backbone.Model.extend({
defaults : {
name : "",
tracks : new TrackCollection,
}
})
var PlaylistCollection = Backbone.Collection.extend({
model : Playlist,
})
创建播放列表集合:
var playlists = new PlaylistCollection;
// create and push the first playlist
playlists.push({ name : "classic" });
// create and push a track in the playlist just created
playlists.last().get("tracks").push({ title : "fur elise" });
// create and push the second playlist
playlists.push({ name : "c2c" });
// create and push a track in the playlist just created
playlists.last().get("tracks").push({ title : "fuya" });
// display first playlist
console.log(JSON.stringify(playlists.at(0).toJSON()))
// display second playlist
console.log(JSON.stringify(playlists.at(1).toJSON()))
这是输出:
{"name":"classic","tracks":[{"title":"fur elise"},{"title":"fuya"}]}
{"name":"c2c","tracks":[{"title":"fur elise"},{"title":"fuya"}]}
问题是,正如我们在输出中看到的那样,2 个播放列表有 2 个曲目“fur elise”和“fuya”。
所以我的问题是为什么?我应该怎么做才能让“fur elise”只出现在名为“classic”的第一个播放列表中,而“fuya”只出现在名为“c2c”的第二个播放列表中?
谢谢你。