Backbone.js collection.models not showing, but the

2019-09-13 03:04发布

问题:

I have a view that's doing a fetch() to a collection and returning some models from the server.

ProductsView = Backbone.View.extend({

    initialize: function() {
        _.bindAll(this, 'render');
        this.collection = new ProductCollection();
        this.collection.fetch({data: {limit : this.options.limit}});

        console.log(this.collection);

        this.render();
    },
    render: function() {

        var template = _.template( $("#product-template").html(), this );
        $(this.el).html( template );
        return this;
    }
});

In the console.log above, I see the object like this:

products.view.js:13
d
_byCid: Object
_byId: Object
length: 7
models: Array[7]
__proto__: x

The models is there, but when I do console.log(this.collection.models) it shows just [], inside the models, is an array of objects like this:

models: Array[7]
0: d
1: d
2: d
3: d
4: d
5: d
6: d

Each of these have attributes with the values that were returned.

Any idea why the models won't show when I use this.collection.models or using get() doesn't work either.

Thanks a lot!

回答1:

In general this.collection.fetch({data: {limit : this.options.limit}}) is an asynchronous operation, so you next line is not necessarily going to print the correct content of the collection.

Instead you should use success and error callbacks the fetch method provides as part of its options parameter (or listen to collection's change event), like so:

this.collection.fetch(
    { 
        data: { limit : this.options.limit },
        success : function(collection, rawresponse) { 
            // do something with the data, like calling render 
        }
    }
);

For completness sake:

this.collection.on('change', function(){ // some handling of the data };
this.collection.fetch();

is the event-based method.