-->

Can't loop over backbone collection

2019-07-15 02:39发布

问题:

It seems that I can't loop through a backbone collection. I've seen this topic in several threads, but none of those solutions help.

render:function () {
        this.$el.html(this.template(this.model.attributes));
        var that = this;


        console.log(this.projects.models);
        _.each(this.projects.models, function(model) { console.log(model); });

        return this;
    }

From this my console only shows Array[2] I would expect to see each model as well. Does anyone know what I'm doing wrong here ?

回答1:

To get your collection content as an array, use the method toJSON (e.g.: collection.toJSON())

Next, to loop over your entire collection, use the each method on the collection instances!

collection.each(function( model ) {
    console.log(model)
});

If this don't show your full collection, then the problem is in how you add items inside your collection, not in the looping logic.