3

Backbone.Model にある種のネストされたコレクションを実装しようとしています。

これを行うには、サーバーの応答を解析して配列をコレクションにラップするアダプター関数と、ヘルパー メソッドを使用せずにオブジェクト全体をシリアル化する関数を上書きする必要があります。私は2番目のものに問題があります。

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 の 2 番目の部分にあります。何らかの理由で

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

true を返さない

誰かが何がうまくいかないのか教えてもらえますか?

4

1 に答える 1

4

アンダースコアhasはこれを行います:

もっている _.has(object, key)

オブジェクトに指定されたキーが含まれていますか? と同じですが、誤ってオーバーライドされた場合に備えobject.hasOwnProperty(key)て、関数への安全な参照を使用します。hasOwnProperty

ただし、プロトタイプに由来するため、プロパティvalueはありません( http://jsfiddle.net/ambiguous/x6577/を参照)。toJSONtoJSON

_(value.toJSON).isFunction()代わりに次を使用する必要があります。

if(_(value.toJSON).isFunction()) {
    // execute toJSON and overwrite the value in attributes
    attributes[key] = value.toJSON();
}
于 2012-08-14T19:04:53.977 に答える