Skip to content Skip to sidebar Skip to footer

Overriding Backbone's Parse Function

I'm trying to use Backbone with an API. The default API response format is: { somemetadatas:xxx , results:yyy } Whether it's a fetch for a single model or a collection. So as far

Solution 1:

You could test if the data you receive is wrapped by a results member and react accordingly. For example,

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

And a Fiddle http://jsfiddle.net/9rCH3/

If you want to generalize this behavior, either derive all your model classes from this base class or modify Backbone's prototype to provide this function :

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

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


Solution 2:

Parse also must be implemented in the Collection.

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

http://backbonejs.org/#Collection-parse


Post a Comment for "Overriding Backbone's Parse Function"