0

私は Backbone.js が初めてで、コレクション ビューで問題が発生しています。これが私がやろうとしていることです:

var customersCollection = new _App.Collections.Customers();
var customersView = new _App.Views.Customers({collection: customersCollection});
customersView.render();

そして、ここにビューがあります-コレクションを反復処理できない理由がわかりません:

_App.Views.Customers = Backbone.View.extend({
    render: function() {
        console.log('Here is my collection');
        console.log(this.collection);
        console.log('Now lets iterate over it...');
        _.each(this.collection, function(item) {
            console.log(item);
        }, this);
        console.log('...done');
        return this;
    }
});

Chrome コンソールに表示される内容:

Here is my collection
child {length: 0, models: Array[0], _byId: Object, constructor: function, url: "/admin/customers/latest.json"…}
    _byId: Object
    length: 5
    models: Array[5]
    __proto__: Surrogate
Now lets iterate over it...
...done 

そのため、コレクションを表示できるのに、それぞれを参照できない理由がわかりません。ありがとう

//解決済み

なぜこれが起こるのかを見つけました。.fetch() が非同期であることを完全に見逃していたため、render() が呼び出されたときに、データがまだコレクションに存在していませんでした。このコードは今私にとってはうまくいくので、テンプレートなどを続けることができます

_App.Views.Customers = Backbone.View.extend({
    initialize: function() {
        this.collection = new _App.Collections.Customers();
        this.collection.on('sync', this.render, this);
        this.collection.fetch();
    },
    render: function() {
        this.collection.each(function(item) {
            console.log(item);
        });
        return this;
    }
});

new _App.Views.Customers();

よろしく、ニコライ

4

1 に答える 1

1

あなたは_.each適切に使用していません。

次のようにする必要があります。

 _.each(this.collection.models, function(item) {
   console.log(item);
 },this);

またはさらに良い:

 this.collection.each(function(item) {
   console.log(item);
 });
于 2013-08-23T22:52:30.133 に答える