我似乎正在使用骨干从服务器正确获取。通过Node.js服务器代码向MongDB集合发出GET请求:
exports.getTeams = function(req,res,next){
var system_db = req.system_db;
var user_id = req.mainUser._id;
var teams = teamModel.getNewTeam(system_db,user_id);
teams.find({}, function (err, items) {
res.json(items);
});
};
我是这样从Backbone获取的:
var teamCollection = new TeamCollection([]);
teamCollection.url = '/api/teams';
teamCollection.fetch(
{success:function(){
console.log('teamCollection length:',teamCollection.length);
console.log('teamCollection[0]:',teamCollection[0]);
}}
);
使用此模型和集合:
var Team = Backbone.Model.extend({
idAttribute: "_id",
urlRoot: 'http://localhost:3000/api/teams'
});
var TeamCollection = Backbone.Collection.extend({
model: Team,
initialize: function() {
this.bind('add', this.onModelAdded, this);
this.bind('remove', this.onModelRemoved, this);
this.bind("change", this.onModelChanged, this);
},
/* parse: function(data) {
//return JSON.stringify(data).objects;
//return JSON.parse(data).objects;
return data.objects;
},*/
onModelAdded: function(model, collection, options) {
console.log("added, options:", options);
},
onModelRemoved: function (model, collection, options) {
console.log("removed, options:", options);
},
onModelChanged: function (model, collection, options) {
console.log('Collection has changed.');
},
comparator: function (model) {
return model.get("_id");
}
});
问题是上面的日志记录在浏览器控制台中记录了以下内容:
它说我从服务器发送4个项目到Backbone客户端,但第一个是未定义的。怎么会这样?
答案 0 :(得分:1)
Backbone.Collection
不是类似于数组的对象:它具有表示模型数量的length
属性,但您无法通过索引访问单个模型,因此
console.log(teamCollection[0]); //undefined
要在给定位置获取模型,请使用collection.at
。尝试
console.log(teamCollection.at(0));