javascript - 覆盖主干的解析函数

标签 javascript backbone.js

我正在尝试将 Backbone 与 API 结合使用。

默认的API响应格式是:

{
somemetadatas:xxx , 
results:yyy
}

无论是获取单个模型还是集合。

据我所知,我可以使用以下方法重写 Backbone parse 函数:

parse: function (response) {
    return response.results;
},

但是我在the documentation中看到过:

parse collection.parse(response)

parse is called by Backbone whenever a collection's models are returned by the server, in fetch. The function is passed the raw response object, and should return the array of model attributes to be added to the collection. The default implementation is a no-op, simply passing through the JSON response. Override this if you need to work with a preexisting API, or better namespace your responses. Note that afterwards, if your model class already has a parse function, it will be run against each fetched model.

因此,如果我有这样的集合获取响应:

{
somemetadatas:xxx , 
results:[user1,user2]
}

集合上的第一个 parse 函数将提取 [user1,user2]

但是医生说:

Note that afterwards, if your model class already has a parse function, it will be run against each fetched model.

因此它将尝试在 user1user2 上查找 response.results;

我需要模型和集合的解析函数,因为模型和集合数据都将位于结果属性下。

但是,如果我获取集合,我不希望对单个数组元素使用模型解析函数。

<小时/>

那么这个问题有解决办法吗?

我想到了一个解决方案,我的集合解析函数将转换如下所示的内容:

{
somemetadatas:xxx , 
results:[user1,user2]
}

变成这样的东西:

[ {results.user1} , {results.user2} ]

这样模型解析函数就不会在集合获取时失败。 但这有点hacky...这个问题有什么优雅的解决方案吗?

<小时/>

顺便说一句,由于我的 API 总是会生成这种形式的结果,是否可以默认覆盖我所有模型和集合的 parse 函数? (抱歉我是个 JS 菜鸟...)

最佳答案

您可以测试您收到的数据是否由 results 成员包装并做出相应 react 。例如,

var M = Backbone.Model.extend({
    parse: function (data) {
        if (_.isObject(data.results)) {
            return data.results;
        } else {
            return data;
        }
    }
});

还有一把 fiddle http://jsfiddle.net/9rCH3/

如果您想推广此行为,请从该基类派生所有模型类,或者修改 Backbone 的原型(prototype)以提供此功能:

Backbone.Model.prototype.parse = function (data) {
    if (_.isObject(data.results)) {
        return data.results;
    } else {
        return data;
    }
};

http://jsfiddle.net/9rCH3/1/

关于javascript - 覆盖主干的解析函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11938500/

相关文章:

JavaScript 数学错误

google-maps - 使用 Backbone.js 首次查看后,Google map 无法正确呈现

jquery - 主干响应有时返回空

javascript - Angular 4 中的多选拖放?

javascript - 如何在 PaperJS 中将图像添加到路径

javascript - 在 React 中使用钩子(Hook)创建事件处理程序的正确方法?

ajax - 将 beforeSend 添加到主干 ajax 调用

backbone.js - Safari 中未触发的主干事件

javascript - Backbone.js 突出显示页面上有大量数据已损坏

javascript - 无法从 <content> 元素调用 View 模型中的函数