Backbone.js的:overwritting的toJSON(backbone.js: over

2019-07-31 00:06发布

我想实现某种嵌套集合的一个Backbone.Model

要做到这一点我必须要被改写的解析服务器响应的适配器功能和数组封装成收集和序列化整个对象没有任何辅助方法的功能。 我有第二个问题。

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

});

现在的问题是在的toJSON第二部分。 由于某些原因

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

没有返回true

有人能告诉我什么错误?

Answer 1:

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


文章来源: backbone.js: overwritting toJSON