这个问题已经被问过好几次了,但没有一个提供的解决方案对我有用。
在这个 Backbone 集合中,我如何访问和循环其模型?
我在下面的代码中尝试了几种方法;包括基于 Mark V. 的答案的补充。
代码也可以在这里找到:http: //jsfiddle.net/LPbsP/3/
(function() {
console.log(Backbone);
window.App = {
Model: {},
Collection: {},
View: {}
};
App.Model.Whatever = Backbone.Model.extend({});
App.Collection.Whatever = Backbone.Collection.extend({
model: App.Model.Whatever,
initialize: function(models, options) {
this.getModels();
_.bindAll(this, 'getModelsWithBindAll');
this.getModelsWithBindAll();
console.log(this);
console.log(models);
models.each(function(model) {
console.log(model);
});
},
getModels: function() {
console.log('in getModels');
console.log(this);
whateverCollection.each(function(model) {
console.log(model);
console.log(model.toJSON());
});
},
getModelsWithBindAll: function() {
console.log('in getModelsWithBindAll');
console.log(this);
whateverCollection.each(function(model) {
console.log(model);
console.log(model.toJSON());
});
}
});
var whateverCollection = new App.Collection.Whatever([
{
name: 'jim',
title: 'boss'
},
{
name: 'tom',
title: 'worker'
}
]);
console.log('program code');
console.log(whateverCollection);
})();
结果:
Object (Backbone)
in getModels
r (length: 0, models: Array[0] ... )
Cannot call method 'each' of undefined
以下是我引用的其他问题: