我需要迭代一个主干集合,并获得一个从集合中的模型派生出来的对象数组。
问题是,我不知道如何让集合访问在创建给出的对象中的模型定义时定义的方法: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的误解而产生的其他一些架构错误
任何帮助都是非常感谢的,非常感谢!
编辑
问题是,实际上这段代码中存在一个bug。当填充集合时,它没有引用"TheModel“作为它的模型类型,因此它创建了自己的模型。
定义集合时需要添加这一行代码:model: TheModel
var theCollection = Backbone.Collection.extend({
model: TheModel,
...
});发布于 2012-07-23 19:15:22
而不是使用:
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();
}
);为什么不使用内置的集合版本:
return this.map(function(theModel){
return theModel.get_derived_object();
});不知道这会不会有帮助,但值得一试。
为了记录在案,在new Backbone.Model(的第一个参数中定义的所有方法都是“公共的”,所以您已经掌握了基本知识。
https://stackoverflow.com/questions/11618908
复制相似问题