13

ローカル API からバックボーン コレクションを作成し、ビューを変更してデータを表示しようとしています。コレクション内の fetch() 呼び出しは成功したようで、データを取得しますが、フェッチ操作はコレクション内のモデルを更新しません。

これは、モデルとコレクション用に持っているものです:

var Book = Backbone.Model.extend();

var BookList = Backbone.Collection.extend({

    model: Book,
    url: 'http://local5/api/books',

    initialize: function(){
        this.fetch({
            success: this.fetchSuccess,
            error: this.fetchError
        });
    },

    fetchSuccess: function (collection, response) {
        console.log('Collection fetch success', response);
        console.log('Collection models: ', this.models);
    },

    fetchError: function (collection, response) {
        throw new Error("Books fetch error");
    }

});

そして、私は次のようにビューを作成しました:

var BookView = Backbone.View.extend({

    tagname: 'li',

    initialize: function(){
        _.bindAll(this, 'render');
        this.model.bind('change', this.render);
    },

    render: function(){
        this.$el.html(this.model.get('author') + ': ' + this.model.get('title'));
        return this;
    }

});

var BookListView = Backbone.View.extend({

    el: $('body'),

    initialize: function(){
        _.bindAll(this, 'render');

        this.collection = new BookList();
        this.collection.bind('reset', this.render)
        this.collection.fetch();

        this.render();
    },

    render: function(){
        console.log('BookListView.render()');
        var self = this;
        this.$el.append('<ul></ul>');
        _(this.collection.models).each(function(item){
            console.log('model: ', item)
            self.appendItem(item);
        }, this);
    }

});

var listView = new BookListView();

私のAPIは次のようなJSONデータを返します:

[
    {
        "id": "1",
        "title": "Ice Station Zebra",
        "author": "Alistair MacLaine"
    },
    {
        "id": "2",
        "title": "The Spy Who Came In From The Cold",
        "author": "John le Carré"
    }
]

このコードを実行すると、コンソールに次のように表示されます。

BookListView.render() app.js:67
Collection fetch success Array[5]
Collection models:  undefined 

これは、フェッチ呼び出しがデータを正常に取得していることを示していますが、モデルにはデータが入力されていません。ここで私が間違っていることを誰かに教えてもらえますか?

4

2 に答える 2

12

あなたのfetchSuccess関数には があってはなりcollection.modelsませんthis.models

console.log('Collection models: ', collection.models);

@Pappaからの提案を検討してください。

于 2013-10-20T13:21:58.780 に答える
8

BookList コレクションで fetch を 2 回呼び出しています。1 回は初期化時、もう 1 回は BookListView の初期化時です。コレクションがインスタンス化された時点で、それ自体を設定することは悪い習慣と見なされます。また、初期化呼び出し内でビューを 2 回レンダリングしています。1 回は「reset」イベントに応答して、次にそれを直接呼び出しています。

BookList コレクションから初期化関数を完全に削除し、 this.render(); への呼び出しを削除することをお勧めします。BookListView の初期化呼び出しの最後に。

于 2013-10-20T11:56:54.200 に答える