javascript - 在 Backbone 模型中定义公共(public)方法

标签 javascript backbone.js backbone-relational

我需要遍历主干集合并获取从集合中的模型派生的对象数组。

问题是我不知道如何让集合访问在以下对象中创建模型定义时定义的方法: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/

相关文章:

javascript - 为什么 Chrome 控制台在 {} + {} 和 {} + {} 之间给出不同的结果;

javascript - 在同一页面中导航 anchor 标记时关闭左滑菜单?

javascript - 无法使用 Backbone.js 将数据保存到 localStorage

javascript - 将 View 放入模型中是不好的行为吗? ( Backbone .js)

javascript - 如何在 React 中修改具有子级多个级别的父 DOM 上的状态

javascript - 搜索文本框在文本框上显示元素

javascript - 在 Backbone.js 中设置自定义 header 不起作用

javascript - Backbone : TypeError: Unedfined is not a function

javascript - 如何使用 Backbone.js 从嵌套的 JSON 构建集合/模型

javascript - 在不发出额外请求的情况下获取 Backbone 模型父关系