我需要遍历主干集合并获取从集合中的模型派生的对象数组。
问题是我不知道如何让集合访问在以下对象中创建模型定义时定义的方法: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();
}
);
}
});
我不确定这里哪里出错了,但我有一些猜测: * 该集合没有以它应该的方式迭代它的模型 * 公共(public)方法不能在 Backbone.Model.extend({}) 中定义 * 我在错误的地方寻找公共(public)方法 * 其他一些架构错误源于对 Backbone.js 的使用方式的误解
感谢任何帮助,非常感谢!
编辑
问题在于这段代码中实际上存在一个错误。填充集合时,它没有引用“TheModel”作为其模型类型,因此它创建了自己的模型。
在定义集合时需要添加这行代码:model: TheModel
var theCollection = Backbone.Collection.extend({
model: TheModel,
...
});
最佳答案
而不是使用:
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(
) 的第一个参数中定义的所有方法都是“公共(public)的”,因此您已经掌握了正确的基础知识。
关于javascript - 在 Backbone 模型中定义公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11618908/