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!
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 thecollection.Instead you should use
successanderrorcallbacks thefetchmethod provides as part of itsoptionsparameter (or listen to collection’schangeevent), like so:For completness sake:
is the event-based method.