Backbone fetch无法正确获取

时间:2015-01-16 09:09:21

标签: javascript backbone.js

我似乎正在使用骨干从服务器正确获取。通过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");
    }
});

问题是上面的日志记录在浏览器控制台中记录了以下内容:

enter image description here

它说我从服务器发送4个项目到Backbone客户端,但第一个是未定义的。怎么会这样?

1 个答案:

答案 0 :(得分:1)

Backbone.Collection不是类似于数组的对象:它具有表示模型数量的length属性,但您无法通过索引访问单个模型,因此

console.log(teamCollection[0]); //undefined

要在给定位置获取模型,请使用collection.at。尝试

console.log(teamCollection.at(0));

这些行为的演示http://jsfiddle.net/nikoshr/013gjpny/