how to override Backbone's parse function?

后端 未结 2 511
既然无缘
既然无缘 2020-12-22 11:53

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

相关标签:
2条回答
  • 2020-12-22 12:17

    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

    0 讨论(0)
  • 2020-12-22 12:22

    From Backbone Parse docs

    Collection = Backbone.Collection.extend({
        model: YourModel,
        parse: function(response){
            return response.items;
        }
    });
    
    0 讨论(0)
提交回复
热议问题