Reputation: 4776
Hello I'm looking for some way to make async call of SomeFunc() just after the collection.fetch()
is done. Something like this:
this.collection.fetch(function(){
console.log('Fetch is done so I'm going to render the view!');
})
Why I want it:
I have the view which renders some collection. Entire data in this collection I'm getting from server-side from REST API with the fetch()
function. And after fetch() it I'm trying to render the view. But in the time when render starts fetch() still is not finished so the view is rendered with the empty collection. What is the Backbone
way to figure it out?
Thx for any advance.
Upvotes: 1
Views: 115
Reputation: 1781
You could tidy this up a little by making use of jQuery's deferred object:
http://api.jquery.com/deferred.then/
this.collection.fetch().then(this.done, this.fail);
// .. somewhere else ...
done : function () {
console.log('yey');
},
fail : function () {
console.log('ney');
}
By the way I know that you can use events for similar purposes but if you take what the manual says at face value:
"Note that fetch should not be used to populate collections on page load — all models needed at load time should already be bootstrapped in to place. fetch is intended for lazily-loading models for interfaces that are not needed immediately: for example, documents with collections of notes that may be toggled open and closed."
Then you'll probably end up pulling your data as needed, probably through a method that wraps around and calls fetch in the way I've demonstrated.
Upvotes: 3
Reputation: 14334
I disagree with using the success
and error
callbacks. They do not leverage the usefulness of Backbone.Collection
in the least. You need to be using backbone events wherever you can! Take a look at binding to the collection's 'reset' event, which is fired after a successful fetch. Try doing something like this in your view's initialize
method:
initialize: function () {
this.collection.bind('reset', this.render, this);
},
Much less code, much cleaner, and utilizes probably the most useful part of the library: events!
Upvotes: 2
Reputation: 6039
Just use the success , error callbacks:
this.collection.fetch({
success: function(){
console.log("Fetch is done so I'm going to render the view!");
},
error: function() {...}
})
Upvotes: 0