1

バックボーンを使用するアプリケーションがありますがfetch()、コレクションのメソッドを呼び出すと、undefinedが返されます。

// App

(function () {

    window.app = {};
    app.collections = {};
    app.models = {};
    app.views = {};

    $(function () {
        app.collections.complaintTypes = new app.collections.ComplaintTypesCollection();
        app.views.complaintTypesView = new app.views.ComplaintTypesView({ collection: app.collections.complaintTypes });
    });

})();

// Collections

(function (collections, model) {
    collections.ComplaintTypesCollection = Backbone.Collection.extend({
        initialize: function () {
            this.fetch();
        },
        model: model,
        url: '/api/ComplaintTypes'
    });
})(app.collections, app.models.ComplaintType);

// Models

(function (models) {
    models.ComplaintType = Backbone.Model.extend({
        idAttribute: 'ComplaintTypeId'
    });
})(app.models);


// Views

(function (views) {
    views.ComplaintTypesView = Backbone.View.extend({
        initialize: function () {
            this.collection.on('reset', this.render, this);
        },
        render: function () {
            console.log(this.collection);
        }
    });
})(app.views);

しかし、これは何も返しませんか?fiddlerを使用して次のURLに移動した場合:/ api / ComplaintTypesデータを取得し直すので、ここで何が間違っているのかわかりません。

4

3 に答える 3

3

コレクションファイルの「モデル」行を削除するとうまくいきました。

于 2012-12-05T13:44:26.333 に答える
1

フェッチは非同期です。結果を取得する必要がある場合は、「成功」ハンドラーを渡す必要があります。つまり、次のようになります。

function myHandler(models) {

}
...
this.fetch({success: myHandler});
于 2012-09-07T08:25:46.883 に答える
1

問題は、コレクションがまだフェッチされていないときにビューを作成することだと思います(JSの非同期動作のため)。この方法を試してください:

$(function () {
    app.collections.complaintTypes = new app.collections.ComplaintTypesCollection();
    app.collections.complaintTypes.fetch({success:function(){
        app.views.complaintTypesView = new app.views.ComplaintTypesView({ collection: app.collections.complaintTypes });
    }});      
});

コレクションから初期化関数を削除します。

于 2012-09-07T08:27:52.447 に答える