Backbone.js集合提取,无法检索项目

时间:2013-01-08 02:33:57

标签: javascript rest backbone.js fetch backbone-collections

我是Backbone.js的新手,我正在学习一本教程,试图让它适应我的需求 我正在从主应用程序视图调用fetch方法,以便检索要插入集合中的多个对象。 我可以在chrome中看到返回了json数据,fetch函数返回成功但是没有填充集合。

我正在使用IcanHaz进行渲染。它只打印出我在工作模型中定义的默认模型。

 var Job = Backbone.Model.extend({
   defaults: {
        title: 'Not specified',
        status: 0,
        created_at: 'Not specified'
    }
 });


var JobView = Backbone.View.extend({
   render: function () {
        // template with ICanHaz.js (ich)
        this.el = ich.jobRowTpl(this.model.toJSON());
        return this;
    }
});

// define the collection of jobs
var JobCollection = Backbone.Collection.extend({
    model: Job,
    url: '/api/1.0/jobs/'
});


// main app, the collection view
var AppView = Backbone.View.extend({
    tagName: 'tbody', 

    initialize: function() {
        this.jobs = new JobCollection();
        this.jobs.on('all', this.render, this);
        this.jobs.fetch({
                           error: function () {
                             console.log("error!!"); 
                           },
                           success: function () {
                              console.log("no error"); 
                           }
                        }).complete(function () {
                            console.log('done');
                            console.log('length1:' +  this.jobs.length);
                        });
       console.log('length2: '+ this.jobs.length);
    },

    render: function () {
        this.jobs.each(function (job) {
            var tmpjob = new JobView({model: job}).render().el;
            $(this.el).append(tmpjob);
            console.log('job': + this.tmpjob);
        }, this);

        return this;
    }


});

var app = new AppView();
$('#app').append(app.render().el);

在Chrome控制台中我得到了这个:

length2:0
job:undefined 
no error 
done 
Uncaught TypeError: Cannot read property 'length' of undefined //referring to the lenght1 logging

这些是我从network / xhr / response下的chrome检查器获取的数据:

{"count": 2, "next": null, "previous": null, "results": [{"id": 1, "title": "testAlbum", "status": 0, "created_at": "2012-12-31"}, {"id": 2, "title": "testAlbum2", "status": 0, "created_at": "2012-12-31"}]}


我不明白为什么在调用fetch方法之后'jobs'集合存在,但是当调用'success'帮助器时,它在fetch块中是未定义的。

为什么集合没有被填充,尽管它返回成功并且json数据从服务器返回?

我很失落。

1 个答案:

答案 0 :(得分:4)

向您的集合添加parse方法,该方法只返回results数组。集合需要是一组模型,而不是整个JSON响应。

Backbone docs解释了如何使用parse