【发布时间】:2014-06-16 07:02:02
【问题描述】:
我正在使用 yoeman 脚手架来创建和构建 Backbone 项目。我正在尝试下面的代码无法在视图的初始化块中获取集合的数据。我在控制台中没有收到任何错误。我试图调试,但它没有成功阻止。谁能告诉我在 Backbone View 中使用集合的正确方法。
contacts.json
[
{
"id": 1,
"name": "first name",
"mobile": "xxx-xxx-xxxx",
"email": "anshuls@abc.com"
},
{
"id": 2,
"name": "second name",
"mobile": "xxx-xxx-xxxx",
"email": "anshuls@abc.com"
}
]
//模型
define([
'underscore',
'backbone'
], function (_, Backbone) {
'use strict';
var ContactModel = Backbone.Model.extend({
initialize: function() {
},
defaults: {
name:null,
mobile:null,
email:null,
avatar:null
}
});
return ContactModel;
});
//采集
define([
'underscore',
'backbone',
'models/contact'], function (_, Backbone, ContactModel) {
'use strict';
var ContactCollection = Backbone.Collection.extend({
model: ContactModel,
url: 'scripts/json/contacts.json',
initialize: function () {
}
});
return ContactCollection;
});
//查看
define([
'jquery',
'underscore',
'backbone',
'templates',
'../views/contact',
'../collections/contact'
], function ($, _, Backbone, JST, ContactView, ContactCollection) {
'use strict';
var ContactsView = Backbone.View.extend({
template: JST['app/scripts/templates/contacts.hbs'],
initialize: function () {
var self = this;
this.collection = new ContactCollection();
this.collection.fetch({
success: function (collection,response) {
console.log('Collection fetch success' + response);
console.log('Collection models: ' + collection.models);
}
});
}
})
return ContactsView;
});
【问题讨论】:
-
尝试添加这个
parse: function(response) { return response; }- 有时 Backbone 需要通过 parse 方法传递 .json 文件。 -
它不在集合的解析块中,但初始化块正在调用集合对象的创建。
标签: backbone.js backbone-views backbone-events backbone.js-collections