【发布时间】:2013-01-08 02:33:57
【问题描述】:
我是 Backbone.js 的新手,我正在学习一个试图使其适应我的需求的教程。
我正在从主应用程序视图调用 fetch 方法,以便检索要插入到集合中的多个对象。
我可以在 chrome 中看到返回了 json 数据,fetch 函数返回成功但未填充集合。
我正在使用 IcanHaz 进行渲染。它只打印出我在 Job 模型中定义的默认模型。
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 数据是从服务器返回的?
我很迷茫。
【问题讨论】:
标签: javascript rest backbone.js fetch backbone.js-collections