質問

基本的に、ノードサーバーにGETリクエストを送信しようとしているため、ブログ投稿を取得してリンクを作成できます。私はします collection.fetch, 、Get Requestを完了しました(Node Serverが適切なオブジェクトを送信していることを記録します)。モデルは正しいデータを正常に解析しますが、コレクションを使用しようとすると、空が空いていると表示されます。これがコードです:

var mdm = mdm || {};

// MODEL
mdm.Post = Backbone.Model.extend({
        parse: function( response ) {
        response.id = response._id;
        console.log(response); // logs the two documents
        return response;
    }
});

// COLLECTION
mdm.Posts = Backbone.Collection.extend({
    model: mdm.Post,
    url: '/api/posts'
});

// MODEL VIEW
mdm.LinkView = Backbone.View.extend({
    template: _.template( $('#link_template').html() ),

    render: function() {
        this.$el.html( this.template( this.model.toJSON() ));
        return this;
    }
});

// COLLECTION VIEW
mdm.LinksView = Backbone.View.extend({
    el: '#link_list',

    initialize: function() {
        this.collection = new mdm.Posts();
        this.collection.fetch({reset: true});
                // makes the request properly, but collection is empty
        this.render();
                // never gets called because the collection is empty
        console.log(this.collection.length); 
                // logs a length of 0
    },

    render: function() {
        // renders collection
    }
});

$(function() {
    new mdm.LinksView();
});

データは送信されており、モデルで解析されているため、コレクションがどのようなものになっているのかわかりません。どんな助けも大歓迎です。

役に立ちましたか?

解決

あなたがあなたの見解でモデルを見ていない最も可能性が高い理由は、レンダリングが非同期の前に起こっているからです fetch 完全です。

以下のようなものはうまくいくでしょう:

mdm.LinksView = Backbone.View.extend({
    el: '#link_list',

initialize: function() {
    this.collection = new mdm.Posts();
    this.listenTo(this.collection, 'reset', this.render);
    this.collection.fetch({reset: true});
}

上記のコードは、のリスナーを設定します reset のイベント collection と実行します render それが起こったときに機能します。

また、渡すこともできます successerror ハンドラーに fetch レンダリング関数も手動で呼び出します。

this.collection.fetch({
    success: _.bind(function() { 
        this.render(); }, this)
});

お役に立てれば!

他のヒント

@fbyniteのコメントに従って、問題はに関連していました fetch 非同期であること。コレクションビューに次の変更を加えましたが、それはトリックを行いました。

initialize: function() {
    var self = this;
    this.collection = new mdm.Posts();
    this.collection.fetch({reset: true,
        success: function() {
            self.render();
            console.log(self.collection.length);
        }
    });
},

コードはバックボーンチュートリアルからの変更であるため、他のユーザーも同様の問題に遭遇する可能性があります。 http://addyosmani.github.io/backbone-fundamentals/#exercise-2-book-library-- your-firstful-backbone.js-app

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top