0

ビューでレンダリングしようとしているバックボーン コレクションがあります。JSON データは正しいようですが、ビュー内から値にアクセスできません。

基本的なコレクションは次のとおりです。

define(['backbone', 'BaseModel'], function(Backbone, BaseModel) {

    var BaseCollection = Backbone.Collection.extend({

         model: BaseModel,
         url: "/collection/get?json=true",

         initialize: function() {}
    });

    return BaseCollection;

});

ビューは次のとおりです。

define(['backbone', 'BaseCollection'], function(Backbone, BaseCollection) {

    var BaseView = Backbone.View.extend({

        el: $('#baseContainer'),
        template: _.template($('#baseTemplate').html()),

        initialize: function() {
            _.bindAll(this);
            this.collection = new BaseCollection();
            this.collection.bind('all', this.render, this);
            this.collection.fetch();
        },
        render: function() {   

            //This returns 3 objects which is correct based on the JSON data being returned from the server
            console.log(this.collection.toJSON());

            var html = this.template(this.collection.toJSON());
            this.$el.html(html);
            return this;
        },

    });

    return BaseView;

});

this.renderコレクション内のモデルごとに反復する必要があると思います。しかし、すべての反復が完了するまで「レンダリング」するべきではないため、よくわかりません。

どんな提案も素晴らしいでしょう!ありがとうございました!

4

1 に答える 1

4

名前を介してテンプレートにモデルへのアクセスを許可する必要があります。これを行う場合:

var html = this.template(this.collection.toJSON());

関数に配列を渡すことになりtemplateますが、通常はコンテキスト オブジェクト (名前と値のペア) が必要です。これを試して:

var html = this.template({collection: this.collection});

次に、テンプレートで、collection.each反復子関数または反復/フィルタリング/マップなどのアンダースコア ユーティリティ メソッドのいずれかを使用して、それらを反復処理できます。また、テンプレートにコレクションへのアクセスを許可する場合は、toJSON を使用しないことをお勧めします。toJSONHTTP リクエストを作成する場合はそのままにしておくのが最適です。

于 2012-06-27T20:24:23.067 に答える