首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在主干模型中定义公共方法

问在主干模型中定义公共方法
EN

Stack Overflow用户
提问于 2012-07-23 19:10:24
回答 1查看 960关注 0票数 1

我需要迭代一个主干集合,并获得一个从集合中的模型派生出来的对象数组。

问题是,我不知道如何让集合访问在创建给出的对象中的模型定义时定义的方法:Backbone.Model.extend({})

--这是我到目前为止所使用的体系结构的一个例子:

代码语言:javascript
复制
// 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

代码语言:javascript
复制
var theCollection = Backbone.Collection.extend({
    model: TheModel,
    ...
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-23 19:15:22

而不是使用:

代码语言:javascript
复制
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();
     }
);

为什么不使用内置的集合版本:

代码语言:javascript
复制
return this.map(function(theModel){
    return theModel.get_derived_object();
});

不知道这会不会有帮助,但值得一试。

为了记录在案,在new Backbone.Model(的第一个参数中定义的所有方法都是“公共的”,所以您已经掌握了基本知识。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11618908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档