Reputation: 35973
I have a strange problem into my app. When I render a collection it was "empty" if I print it but when I console.log this collection inside collection there is twho arrays inside models. Well this is my script:
define([
'jquery',
'underscore',
'backbone',
'text!templates/folder.html',
'models/folder',
'collections/folder',
], function($, _, Backbone, FolderTemplate, FolderModel, FolderCollection){
var FolderView = Backbone.View.extend({
el:$('#folder'),
template:_.template(FolderTemplate),
initialize: function(){
this.render();
},
render: function(){
console.log(this.collection.models);
}
});
return FolderView;
});
to call the view I use it inside another app:
this.folders = new FolderCollection();
this.folders.fetch({ data: { dir: 'uploads'} });
this.foldersView = new FolderView({collection: this.folders});
With this app console.log(this.collection.models);
is empty
But if I make something like this with a setTimeOut it works the console.log return me the right arrays:
define([
'jquery',
'underscore',
'backbone',
'text!templates/folder.html',
'models/folder',
'collections/folder',
], function($, _, Backbone, FolderTemplate, FolderModel, FolderCollection){
var FolderView = Backbone.View.extend({
el:$('#folder'),
template:_.template(FolderTemplate),
initialize: function(){
var here = this;
setTimeout(function(){
here.render();
},800);
},
render: function(){
console.log(this.collection.models);
}
});
return FolderView;
});
How can I use this.render()
without a setTimeOut, because I think isn't correct or not logic to make something like that.
Thanks
Upvotes: 1
Views: 1143
Reputation: 55740
You can listen to the reset
event which will invoke the render
method
Replace
initialize: function(){
var here = this;
setTimeout(function(){
here.render();
},800);
},
with
initialize: function(){
this.listenTo(this.collection, 'reset', this.render);
},
Upvotes: 3
Reputation: 14766
Try with this:
initialize: function(){
var self = this;
this.collection.fetch({
success: function(){
self.render();
}
});
}
Upvotes: 2
Reputation: 6342
The reason you're having to do this is because this.folders.fetch
takes time. Instead of setting a timeout you should be using events instead. Collection.fetch
will fire a change
event on success.
So, instead consider something like:
this.collection.on("change", this.render);
Upvotes: 0