backbone.js: overwritting toJSON

2019-03-16 23:07发布

I am trying to implement some sort of nested collections in a Backbone.Model

To do this I have to overwrite the adapter functions which parse the server response and wrap the array into a collection and the function which serializes the whole object without any helper methods. I am having problems with the second one.

var Model = Backbone.Model.extend({

    urlRoot: "/model",

    idAttribute: "_id",

    // this wraps the arrays in the server response into a backbone  collection
    parse: function(resp, xhr) {
        $.each(resp, function(key, value) {
            if (_.isArray(value)) {
                resp[key] = new Backbone.Collection(value);
            } 
        });
        return resp;
    },

    // serializes the data without any helper methods
    toJSON: function() {
        // clone all attributes
        var attributes = _.clone(this.attributes);

        // go through each attribute
        $.each(attributes, function(key, value) {
            // check if we have some nested object with a toJSON method
            if (_.has(value, 'toJSON')) {
                // execute toJSON and overwrite the value in attributes
                attributes[key] = value.toJSON();
            } 
        });

        return attributes;
    }

});

The problem is now at the second part in toJSON. For some reason

_.has(value, 'toJSON') !== true

doesn't return true

Could somebody tell me what is going wrong?

1条回答
闹够了就滚
2楼-- · 2019-03-17 00:00

Underscore's has does this:

has _.has(object, key)

Does the object contain the given key? Identical to object.hasOwnProperty(key), but uses a safe reference to the hasOwnProperty function, in case it's been overridden accidentally.

But your value won't have a toJSON property since toJSON comes from the prototype (see http://jsfiddle.net/ambiguous/x6577/).

You should use _(value.toJSON).isFunction() instead:

if(_(value.toJSON).isFunction()) {
    // execute toJSON and overwrite the value in attributes
    attributes[key] = value.toJSON();
}
查看更多
登录 后发表回答