1

私はバックボーンを初めて使用し、テスト用のローカル JSON ファイルを使用して、モデルとその中にネストされたコレクションをセットアップしようとしています。現在、次のようなものがあります。

var MyModel = Backbone.Model.extend({
    coll: null,
    initialize: function (attributes, options) {
        this.setData(attributes);
    },
    setData: function (data) {
        this.set("key1", data.key1);
        this.set("key2", data.key2);

        var coll = this.coll ? this.coll.reset(data.collData) : new MyCollection(data.collData);
        this.set("coll", coll);
    }
});
// ...
var myModel = new Model(jsonLoadedFromLocalFile);

Model.fetch()ただし、サーバーがデータを返す準備ができたら、 andを使用するだけで、それらがandCollection.fetch()を呼び出し、それがデータを解析するのに適切な場所であると理解しています (私の一見あまりにも手動とは対照的に)。Model.parse()Collection.parse()parse()setData()

ネストされたコレクションを持つモデルをテストするためにダミー データを読み込むには、どのような方法が適していますか?

4

1 に答える 1

1

これはトリックを行うようです:

var MyModel = Backbone.Model.extend({
    defaults: {
        key1: "",
        key2: "",
        coll: null
    },
    initialize: function (attributes, options) {
        this.fetch({ url: attributes.url });
    },
    parse: function (response) {
        this.set("key1", response.key1);
        this.set("key2", response.key2);

        var coll = this.coll ? this.coll.reset(response.collData) : new MyCollection(response.collData);
        this.set("coll", coll);
    }
});
// ...
var myModel = new Model({ url: localJsonURL });

@muneebShabbir に感謝します。

于 2013-07-02T04:31:01.653 に答える