我需要遍历主干集合并获取从集合中的模型派生的对象数组。
问题是我不知道如何让集合访问在给定对象内创建模型定义时定义的方法:Backbone.Model.extend({})
这是我目前所拥有的架构示例:
// THE MODEL
var TheModel = Backbone.Model.extend({
// THE FOLLOWING IS NOT AVAILABLE AS A METHOD OF THE MODEL:
// This isn't the actual method, but I though it might be helpful to
// to demonstrate that kind of thing the method needs to do (manipulate:
// map data and make it available to an external library)
get_derived_object: function(){
return this.get('lat') + '_' this.get('lon');
}
});
// THE COLLECTION:
var TheCollection = Backbone.Collection.extend({
// Use the underscore library to iterate through the list of
// models in the collection and get a list the objects returned from
// the "get_derived_object()" method of each model:
get_list_of_derived_model_data: function(){
return _.map(
this.models,
function(theModel){
// This method is undefined here, but this is where I would expect
// it to be:
return theModel.get_derived_object();
}
);
}
});
我不确定我哪里出错了,但我有一些猜测: * 集合没有以应有的方式迭代它的模型 * 不能在 Backbone.Model.extend({}) 中定义公共方法* 我在寻找公共方法的错误位置 * 由于对 Backbone.js 的使用方式的误解而导致的其他一些架构错误
任何帮助表示赞赏,非常感谢!
编辑
问题是这段代码实际上有一个错误。当集合被填充时,它没有引用“TheModel”作为它的模型类型,所以它创建了自己的模型。
定义集合时需要添加这行代码:model: TheModel
var theCollection = Backbone.Collection.extend({
model: TheModel,
...
});