首页 文章

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

提问于
浏览
0

我按照教程试图使其适应我的需要 .
我正在从主应用程序视图调用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"}]}

我没有't understand why the '工作' collection exists after calling the fetch method but it is undefined inside the fetch block when the '成功'帮手已被召唤 .

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

我很失落 .

1 回答

  • 4

    parse 方法添加到刚刚返回 results 数组的集合中 . 集合需要是一组模型,而不是整个JSON响应 .

    Backbone docs解释如何使用 parse .

相关问题