我认为我不了解 Backbone 的同步行为。当将数组传递给集合时,一切正常,当尝试从 json 文件或服务器获取完全相同的数据结构时,集合不会被填充。这就是所谓的集合。
define(['backbone',
'jquery',
'views/users',
'collections/user',
],
function(Backbone, $, UsersView, UserCollection){
var App = Backbone.View.extend({
el:'.container',
initialize: function() {
var test = [
{"name":"Someone","email":"some@gmail.com"},
{"name":"Somebodyelse","email":"another@gmail.com"},
{"name":"John","email":"idiot@aol.com"}
];
var userCollection = new UserCollection(test);
new UsersView({collection: userCollection});
}
});
return App;
这在我的用户视图中运行良好。
define(['backbone',
'jquery',
'underscore',
'views/user',
],
function(Backbone, $, _, UserView){
var Users = Backbone.View.extend({
el: $('.userlist'),
initialize: function(){
this.renderAll();
},
renderAll: function() {
this.$el.empty();
this.collection.each(this.render, this);
},
render: function(user){
var userView = new UserView({model: user});
this.$el.append(userView.render().el);
return this;
}
});
return Users;
});
但是当像这样从服务器获取完全相同的 json 时:
define(['backbone',
'jquery',
'views/users',
'collections/user',
],
function(Backbone, $, UsersView, UserCollection){
var App = Backbone.View.extend({
el:'.container',
initialize: function() {
var userCollection = new UserCollection;
userCollection.fetch();
new UsersView({collection: userCollection});
}
});
return App;
});
该集合填充有 1 个模型数组,其中包含四个模型。所以调用this.collection(this.render,this)
只调用render
一次函数。这导致这被记录到控制台:
child {models: Array[0], length: 0, _byId: Object, constructor: function, url: "/users"…}
_byId: Object
_idAttr: "id"
length: 4
models: Array[4]
__proto__: Surrogate
当我像这样在提取中进行一些错误检查时:
userCollection.fetch({
success: function(response) {
console.log(response);
}
然后该集合填充了 4 个模型,而不是 1 个具有 4 个模型的数组,如在控制台中看到的那样:
child {models: Array[4], length: 4, _byId: Object, _idAttr: "id", constructor: function…}
_byId: Object
_idAttr: "id"
length: 4
models: Array[4]
__proto__: Surrogate
我并不擅长使用 javascript,而且我仍在尝试使用模块来解决问题。集合的传递方式或服务器数据有问题吗?