I’m working on a Backbone.js application with multiple “sections”. Each “section” may have multiple routes but share a single collection. Here’s a simple example (with sections “a” and “b”): http://jsfiddle.net/scttnlsn/LW4Ny/
In the example, all the collections are fetched when the router is initialized so that they can be shared across multiple routes without the need to re-fetch in every route handler. This seems fine at first but I am wary of continuing this way when the number of shared collections starts to grow. Additionally, it seems silly to be fetching collections for “sections” that may never even be visited by the user- I would much rather load data on demand.
The obvious alternative is to fetch the data in each route handler instead of when the router is initialized. This would mean that only data that is actually needed is fetched, however, it still ends up performing unnecessary fetches when moving between routes in the same “section”. There would no longer be any “sharing” of collection data.
What’s a good way to handle this situation? I feel like I need to implement some sort of cache-like structure. Are there existing solutions?
Thanks!
-Scott
Assuming I understand the issue… you could skip fetching on initialization (as in the alternative you describe), but also skip instantiation of the collection altogether until needed. Then declare a factory(ish) method:
Then call it from within each route handler: