编程语言
首页 > 编程语言> > Javascript-bone.js:改写为JSON

Javascript-bone.js:改写为JSON

作者:互联网

我正在尝试在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

有人可以告诉我出什么事了吗?

解决方法:

Underscore’s has这样做:

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.

但您的值将没有toJSON属性,因为toJSON来自原型(请参见http://jsfiddle.net/ambiguous/x6577/).

您应该改用_(value.toJSON).isFunction():

if(_(value.toJSON).isFunction()) {
    // execute toJSON and overwrite the value in attributes
    attributes[key] = value.toJSON();
}

标签:backbone-js,underscore-js,json,javascript
来源: https://codeday.me/bug/20191101/1980077.html