如何覆盖骨干解析功能? [英] how to override Backbone's parse function?

查看:91
本文介绍了如何覆盖骨干解析功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着在我的项目中使用的骨干。但我遇到问题时尝试骨干将覆盖的解析方法。该服务器有发回的数据超过我want.For例如:
我要的是:

I try to use backbone in my project. But I have met problem when try to overide parse method of Backbone. The server has send back more data than I want.For example: What I want is:

[{
   id: "123",
   name: "david"
},{
   id: "456",
   name: "kevin"
}]

但服务器的结果是:

but the server's result is :

{
 total: 1000,
 items:[{
   id: "123",
   name: "david"
},{
   id: "456",
   name: "kevin"
}]
}

所以我想在parse方法处理结果,并只返回数组。我怎样才能做到这一点?当我尝试我得到了错误。我应该怎么办?

so I want process result in parse method and return only the array. How can I do this? When I try I got error. How should I do?

推荐答案

在您的骨干模型,定义解析功能,你会喜欢的方式:

In your backbone model, define the parse function the way you would like:

Model = Backbone.Model.extend({
    parse: function () {
        return {
            id: this.get("id"),
            name: this.get("name")
        }
    }
});

不过,这将是更好的模型初始化处理和设置数据,像这样:

But, it would be better to handle and set the data in the model initializer, like so:

Model = Backbone.Model.extend({
    initialize: function (attrs) {
        try {
            //TODO HERE: test for correct values and throw errors

            // set object variables here
            this.set({
                name: attrs.name,
                id: attrs.id
            });

        } catch (e) {
            console.log(e);
        }
    }
});

没有必要现在覆盖解析功能。你知道你的模型是处理数据这样是好的,您所设置的变量,它包含的内容。这避免了无效的数据很多错误。

No need to overwrite the parse function now. This way you know the data that your model is handling is good, and you set what variables it contains. This avoids many errors from invalid data.

数组中的每一项都应该真正成为一个子模型,这就是我上面写的。你父模型应该是这样的:

Each item in the array should really be a submodel, which is what I have written above. Your parent model should look like:

Model = Backbone.Model.extend({
    initialize: function (items) {
        this.subModels = [];
        items.forEach(function (item) {
            this.subModels.push( new SubModel(item) )
        });
    }
});

或者作为一个集合:

Or as a collection:

Collection = Backbone.Collection.extend({
    model: ItemModel,
});

要,你会通过response.items

To which you would pass response.items

这篇关于如何覆盖骨干解析功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆