Question

So what I'm wanting to do is have Backbone fetch all my collections when the router starts, and then keep all the collections and not have to re-fetch and reload all the collections while moving to different routes in the router. Does anyone know a way to do this?

Was it helpful?

Solution

From Backbone.js docs:

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.

This is what I meant in my comment:

<script>
  define("data", function() {
    return <?php echo json here ?>;
  });
</script>

Then you can have var data = require("data"); and use it to init Backbone models/collections. I'm not sure this is the right way of doing it.

OTHER TIPS

Well, backbone does this by default. Just add code to your router to create an instance of each collection and call fetch() once on each collection. Then make sure the rest of your app just uses those same collection instances and does NOT call fetch() on them again. It's really that simple.

However, I presume you want other bits of your application to be able to call fetch() and have this silently use cached data if needed. This a considered a hard problem to do correctly, but a naive and simple implementation would be to simply store an isCached flag as a property of your collection and check that in your overridden fetch() method and just return without doing anything if your collection data is already loaded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top