javascript - Backbone.js - Sharing collections across multiple routes -
i'm working on backbone.js application multiple "sections". each "section" may have multiple routes share single collection. here's simple example (with sections "a" , "b"): http://jsfiddle.net/scttnlsn/lw4ny/
in example, collections fetched when router initialized can shared across multiple routes without need re-fetch in every route handler. seems fine @ first wary of continuing way when number of shared collections starts grow. additionally, seems silly fetching collections "sections" may never visited user- rather load data on demand.
the obvious alternative fetch data in each route handler instead of when router initialized. mean data needed fetched, however, still ends performing unnecessary fetches when moving between routes in same "section". there no longer "sharing" of collection data.
what's way handle situation? feel need implement sort of cache-like structure. there existing solutions?
thanks!
-scott
assuming understand issue... skip fetching on initialization (as in alternative describe), skip instantiation of collection altogether until needed. declare factory(ish) method:
getorfetchcollection: function(collectionid) { var collection = this[collectionid]; if(!collection) { collection = this[collectionid] = new backbone.collection(); collection.url = urlfor(collectionid); collection.fetch(); } return collection; }
then call within each route handler:
a1: function() { var view = new view({ title: 'a1', collection: this.getorfetchcollection('a') }); show(view); }
Comments
Post a Comment