how to override Backbone's parse function?

2019-01-29 09:33发布

问题:

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"
}]
}

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?

回答1:

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,
});

To which you would pass response.items



回答2:

From Backbone Parse docs

Collection = Backbone.Collection.extend({
    model: YourModel,
    parse: function(response){
        return response.items;
    }
});