Using Backbone.js, I have a collection that I instanctiate, X. After instantiating it, I immediately called X.fetch() such that the data can be loaded from the server as soon as possible. I then pass X into various views that will operate on the collection.
What is the best way for these views do differentiate between when the collection is simply loading (and thus empty) and when it is loaded but actually empty? I would like my views to show appropriate “loading…” text up until the collection has pinged the server. At which point, I would like them to say “It looks like there’s nothing here. Perhaps you should add something.”
I was thinking of maybe listening to the reset event on the collection in each respective view, but this seems rather fragile to me. What happens if the reset event has already fired before the view attaches its listener? Is there a good pattern to inspect the state of a collection to find out if it’s been fetched?
fetchmethod is asynchronous based on asynchronous nature of AJAX.Therefore you need to implement an event-driven behavior.
Update
Based on your comments to my answer I can propose another idea.
Namely you can set
X.isLoaded = true;or any other property like
X.loadedAt = Date.now();in
successcallback, so other code can check for the state of this property.But though I see a kind of bad design here.
You can render your views with preloader showed and in
successcallback trigger some event on which your views will start to work with the collection since it’s loaded and became ready to use.So in total I’m again propose you to use event-driven behavior.
I didn’t test, but here is a representation of my idea:
Documentation