I’m using Backbone with RequireJS, and my View needs to switch between like, say, 20 collections corresponding to respective RESTful APIs.
The “normal” way handles things fine, except that for each API a new Collection needs to be defined, resulting in a hugely bloated codebase:
Collection (x 20 times)
define(function(require) {
var Backbone = require('backbone');
var c = Backbone.Collection.extend({
url: '/path/to/api-1'
});
return new c();
});
View
define(function(require) {
var Backbone = require('backbone'),
c1 = require('./collections/collection-1'),
...
c20 = require('./collections/collection-20');
var v = Backbone.View.extend({
/* Some methods to toggle between Collections here */
});
return v;
});
By only doing return c; inside the Collection, and calling new c({url: /path/to/api-1}); inside the View, I was able to cut down the highly duplicated Collection defines; but now on each new c(); calls, the APIs will always be poked to retrieve a new copy of data, which is a waste to resources and something I do not want.
Is there any way to make Collections “persistent”? Which better meets all of the criteria below:
- For each API’s corresponding Collection, only one
newis performed; - Each Collection can be shared/accessed across different Views defined using RequireJS;
- The definition of the Collection can be reused by all APIs;
- The global namespace is not polluted at all.
Found a rather hackish solution:
Wrap your Collection with another Model:
Then, define a Cache container:
Require both the Cache container and the wrapped Collection in your View module:
This way you get both the benefits of instantiate new Collections with dynamically-generated
$_pathvalues, and being able to cache data fetched from your APIs so long the page is not refreshed – implementlocalStorageif you’d like the data to persist through page refreshes.